How to automatically select all items above the selected one flutter - flutter

I have a custom list view with selectable items.And I am trying to select all items automatically present above the one I selected. For Ex: Suppose there is 10 items in the list view and i selected 5th then it should select all the items available above 5th. i.e(1,2,3,4) and when i deselect 3rd item 1,2,3 items should deselected automatically
return CheckboxListTile(
activeColor: const Color.fromARGB(
255, 243, 243, 243),
checkColor: UIGuide.light_Purple,
selectedTileColor:
UIGuide.light_Purple,
value: value.selecteCategorys
.contains(value.feeList[index]
.installmentName ??
'--'),
onChanged: (bool? selected) async {
value.onFeeSelected(
selected!,
value.feeList[index]
.installmentName,
index,
value.feeList[index].netDue);
},
title: Text(
value.feeList[index].netDue ==
null
? '--'
: value.feeList[index].netDue
.toString(),
textAlign: TextAlign.end,
),
secondary: Text(
value.feeList[index]
.installmentName ??
'--',
),
);

do something like this :
1 - get index of selected item
2 - in the callback fun of checkbox do
let say we have list of items named by items
List<Item> items = [];
foo() {
final upperlist = items.getRange(0, index).toList();
upperlist.forEach((item) {item.selected =true });
items.replaceRange(0, index, upperlist);
setState((){});
}

Note, this example isn't perfect, but it's a working example that can get you thinking, as I don't know the bigger picture
Here's my approach:
get the widget and index of the currently selected value using .indexOf()
loop over all the widgets until the previously gotten index
for (var i = 0; i < _data.indexOf(item); i++) {
_data[i].isChecked = value!;
}
Code example
create a class called CheckBoxModel:
class CheckBoxModel {
bool isChecked = false;
String text = "";
CheckBoxModel({required this.isChecked, required this.text});
}
and then, generated 30 widgets:
final _data = List.generate(
30, (index) => CheckBoxModel(isChecked: false, text: "Item $index"));
and used it correspondingly:
Column(
children: [
for (var item in _data)
CheckboxListTile(
value: item.isChecked,
onChanged: (value) {
setState(() {
for (var i = 0; i < _data.indexOf(item); i++) {
_data[i].isChecked = value!;
}
});
},
title: Text(item.text),
),
],
)
Here's a complete runnable snipppet:
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class CheckBoxModel {
bool isChecked = false;
String text = "";
CheckBoxModel({required this.isChecked, required this.text});
}
final _data = List.generate(
30, (index) => CheckBoxModel(isChecked: false, text: "Item $index"));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Testing(),
),
),
);
}
}
class Testing extends StatefulWidget {
const Testing({Key? key}) : super(key: key);
#override
State<Testing> createState() => _TestingState();
}
class _TestingState extends State<Testing> {
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: [
for (var item in _data)
CheckboxListTile(
value: item.isChecked,
onChanged: (value) {
setState(() {
for (var i = 0; i < _data.indexOf(item); i++) {
_data[i].isChecked = value!;
}
});
},
title: Text(item.text),
),
],
),
);
}
}

Related

How can I only check one checkbox at time?

How can I select/check only one checkbox to be checked at time?
And below is my code
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Checkbox(
checkColor: Colors.white,
value: isChecked,
onChanged: (bool value) {
setState(() {
isChecked = value;
// ignore: unnecessary_statements
passData(certId);
});
},
),
],
)),
Option1 - Using a map to maintain the state
Create a map:
final Map<int, bool> _state = {};
then, check if the value for that index is true/false:
return ListView.builder(itemBuilder: (context, index) {
return CheckboxListTile(
value: _state[index] ?? false,
onChanged: (value) {
setState(() {
_state[index] = value!;
});
},
title: Text(_data[index].text),
);
});
Option 2 - using a model:
class CheckBoxModel {
bool isChecked = false;
String text = "";
CheckBoxModel({required this.isChecked, required this.text});
}
and then, generate a List of 30 widgets:
final _data = List.generate(
30, (index) => CheckBoxModel(isChecked: false, text: "Item $index"));
Now, use a ListView.builder and based on the index, to update the corresponding value:
class Testing extends StatefulWidget {
const Testing({Key? key}) : super(key: key);
#override
State<Testing> createState() => _TestingState();
}
class _TestingState extends State<Testing> {
#override
Widget build(BuildContext context) {
return ListView.builder(itemBuilder: (context, index) {
return CheckboxListTile(
value: _data[index].isChecked,
onChanged: (value) {
setState(() {
_data[index].isChecked = value!;
});
},
title: Text(_data[index].text),
);
});
}
}
See also
Expansion tile trailing icon updates all in list on interaction with one tile. How can I only change the icon for the expanded tile?

how can i change a RadioListTile button selection state after it has been initialized in flutter

I have created a RadioListTile based on a list of string items in an initStat function. But i could not get the radio button to change when it is being selected. If it were in a build function i could just call setState and it would have marked it as selected.
How can i mark it as selected when i have created it at the beginning of the code. below here is the code i have tried, it actually print the selected radioTile value but i could not get it to change the selected state or the radio button selection.
List<String> list = ['Satisfied', 'Not Satisfied', 'Very Satisfied','Neutral'];
String _radioGroupValue = '';
int selectedRadioTile = 0;
void initState() {
super.initState();
selectedRadioTile = 0;
setState(() {
for (int n = 0; n < list.length; n++) {
answersRadio.add(RadioListTile(
value: n,
groupValue: _radioGroupValue,
onChanged: (val) {
print('selected Radio index $val');
setSelectedRadioTile(val);
setState(() {
});
},
title: Text(list[n]),
selected: _radioGroupValue == list[n] ? true : false,
));
}
});
}
setSelectedRadioTile(int val){
setState(() {
selectedRadioTile = val;
});
}
child: Column(children: answersRadio,)
class Example extends StatefulWidget {
const Example({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _Examplestate();
}
}
class _Examplestate extends State<Example> {
List<String> list = [
'Satisfied',
'Not Satisfied',
'Very Satisfied',
'Neutral'
];
String? _radioGroupValue;
List<RadioListTile> answersRadio = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Stateful Widget'),
),
body: Column(
children: [
for (var n in list)
RadioListTile<String>(
value: n,
groupValue: _radioGroupValue,
onChanged: (val) {
_radioGroupValue = val;
setState(() {});
},
title: Text(n),
toggleable: true,
selected: _radioGroupValue == n,
)
],
),
);
}
}
set int _groupValue = -1. define value for value : parameter according your need
Radio(
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.comfortable,
activeColor: AppTheme.primaryColor,
value: 1,
groupValue: _groupValue,
onChanged: (value) {
setState(() {
_groupValue = value as int;
});
},
),

How to Display selected data to another page in flutter

Hi i am new to flutter i have used sample database to get data of 10 users. this data is displayed in list tile with leading item is checkbox (to select / deselect). Now i need help in displaying the selected data on to the other page once i press cart button in the appbar..
here's my main
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_application_http_get/example.dart';
import 'package:flutter_application_http_get/screen.dart';
import 'package:flutter_application_http_get/selected.dart';
import 'package:flutter_application_http_get/sunday_state.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Sunday(),
);
}
}
class Sunday extends StatefulWidget {
const Sunday({Key? key}) : super(key: key);
#override
_SundayState createState() => _SundayState();
}
API Called Here
class _SundayState extends State<Sunday> {
var users = [];
Future getUserData() async {
var res =
await http.get(Uri.https("jsonplaceholder.typicode.com", "users"));
var jsonData = jsonDecode(res.body) as List;
setState(() {
users = jsonData;
});
}
#override
void initState() {
super.initState();
getUserData();
}
final notification = [SundayCheckBoxState()];
late final post;
data from post if checked printed..
getCheckboxItems() {
users.forEach((post) {
if (post['checked'] == true) {
print(post);
}
});
}
here in when onpressed i need to display the checked data on to the other page
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("User Data"),
actions: [
IconButton(
onPressed: getCheckboxItems,
icon: Icon(Icons.shopping_cart))
],
),
body: Container(
child: Card(
margin: EdgeInsets.all(20.0),
child: ListView.builder(
itemCount: users.length,
itemBuilder: (context, i) {
final post = users[i];
return Card(
elevation: 5,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: ListView(shrinkWrap: true, children: [
ListTile(
leading: Checkbox(
value: post['checked'] ?? false,
onChanged: (value) {
setState(() {
post['checked'] = value;
});
}),
title: Text("${post['id']}" + "${post['name']}"),
),
])
));
}),
),
),
);
}
You can try this logic it worked for me :
var _isSelectedCheckBoxArr = [];
var _addSelectedValueArr = [];
Checkbox(
value: _isSelectedCheckBoxArr[i],
materialTapTargetSize:
MaterialTapTargetSize
.shrinkWrap,
onChanged: (s) {
setState(() {
_isSelectedCheckBoxArr[i] =
!_isSelectedCheckBoxArr[i];
});
print(
"$_tag onChanged: (s): $s");
if (s) {
setState(() {
_addSelectedValueArr.add(
"${users[i]}");
});
} else if (!s) {
setState(() {
_addSelectedValueArr
.remove(
users[i]);
});
}
}),
Then on the click of cart button pass the _addSelectedValueArr array in the constructor of the screen you want to display.

Corresponding DropDownButtonFormFields in Flutter

I'm implementing corresponding dropdowns (where the options of the second dropdown depend on the first like so) that uses a list of objects in this format:
List<State> states = [
new State(stateId: 1, stateName: "New York", cities: [
new City(cityId: 1, cityName: "New York City"),
new City(cityId: 2, cityName: "Buffalo") ...
And the widget code is like so:
children: <Widget>[
DropdownButtonFormField<int>(
decoration: InputDecoration(labelText: 'State'),
value: selectedStateId,
items: states.map((State state) {
return new DropdownMenuItem<int>(
value: state.stateId,
child: new Text(states.singleWhere((x) => x.stateId == state.stateId).stateName),
);
}).toList(),
onChanged: (int newStateId) {
setState(() {
this.selectedCityId = states.singleWhere((x) => x.stateId == newStateId).cities[0].cityId; // set to first city for this state
this.selectedStateId = = newStateId;
});
},
),
DropdownButtonFormField<int>(
decoration: InputDecoration(labelText: 'City'),
value: selectedCityId,
items: states.singleWhere((x) => x.stateId == selectedStateId)
.cities
.map((City city) {
return new DropdownMenuItem<int>(
value: city.cityId,
child: new Text(states
.singleWhere((x) => x.stateId == selectedStateId).cities.singleWhere((x) => x.cityId == city.cityId).cityName),
);
}).toList(),
onChanged: (int newCityId) {
setState(() {
this.selectedCityId = newCityId;
});
},
)
],
When I change the State dropdown in this example, I get an error:
"There should be exactly one item with [DropdownButton]'s value: 1.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value".
The "1" in the above error corresponds to whatever the selected city value was prior to changing the state, so I know that the error relates to the fact that it's still looking for the old selectedCityId and it is no longer in the item list, but I'm not sure why as I've changed that value in setState. A key to this issue, I believe, is the same exact code works if I just change the DropDownButtonFormField to regular DropDownButtons, but I'd like to use the built in label text that comes along with the former.
Edit
You can use key: UniqueKey() int City DropdownButtonFormField
DropdownButtonFormField<int>(
key: UniqueKey(),
decoration: InputDecoration(labelText: 'City'),
You can copy paste run full code below
You can set selectedStateId and selectedCityId to states's attribute
You can not directly set to a value like selectedStateId = 1, because system will compare address
code snippet
int selectedStateId;
int selectedCityId;
#override
void initState() {
selectedStateId = states[0].stateId;
selectedCityId = states[0].cities[0].cityId;
super.initState();
}
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class City {
int cityId;
String cityName;
City({this.cityId, this.cityName});
}
class CountryState {
int stateId;
String stateName;
List<City> cities;
CountryState({this.stateId, this.stateName, this.cities});
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
List<CountryState> states = [
CountryState(stateId: 1, stateName: " York", cities: [
City(cityId: 1, cityName: "York City"),
City(cityId: 2, cityName: "Buffalo")
]),
CountryState(stateId: 2, stateName: "A", cities: [
City(cityId: 3, cityName: "A1"),
City(cityId: 4, cityName: "A2")
])
];
int selectedStateId;
int selectedCityId;
#override
void initState() {
selectedStateId = states[0].stateId;
selectedCityId = states[0].cities[0].cityId;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButtonFormField<int>(
decoration: InputDecoration(labelText: 'State'),
value: selectedStateId,
items: states.map((CountryState state) {
return DropdownMenuItem<int>(
value: state.stateId,
child: Text(states
.singleWhere((x) => x.stateId == state.stateId)
.stateName),
);
}).toList(),
onChanged: (int StateId) {
setState(() {
this.selectedCityId = states
.singleWhere((x) => x.stateId == StateId)
.cities[0]
.cityId; // set to first city for this state
this.selectedStateId = StateId;
});
},
),
DropdownButtonFormField<int>(
key: UniqueKey(),
decoration: InputDecoration(labelText: 'City'),
value: selectedCityId,
items: states
.singleWhere((x) => x.stateId == selectedStateId)
.cities
.map((City city) {
return DropdownMenuItem<int>(
value: city.cityId,
child: Text(states
.singleWhere((x) => x.stateId == selectedStateId)
.cities
.singleWhere((x) => x.cityId == city.cityId)
.cityName),
);
}).toList(),
onChanged: (int CityId) {
setState(() {
this.selectedCityId = CityId;
});
},
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
I posted this example on the Flutter issues board and they could not duplicate on the latest stable version (1.20.2 as of this comment). I upgraded my flutter version (I was on 1.17.1) and the same code ran without issue, so for anyone experiencing the same issue I suggest updating your flutter version.

How can I handle a list of checkboxes dynamically created in flutter?

Using flutter, I am trying to build a list of values with some text and a customized checkbox next to it. Tapping anywhere on the text or checkbox should show the enabled state and tapping again should disable it. I am unsure how to handle the state of each checkbox separately. I tried using CheckBoxListTile too but I am not sure how I can achieve what I want. Can someone provide any examples?
Here's some sample code for CheckboxListTile. You can find more examples in the gallery.
import 'package:flutter/material.dart';
class Demo extends StatefulWidget {
#override
DemoState createState() => new DemoState();
}
class DemoState extends State<Demo> {
Map<String, bool> values = {
'foo': true,
'bar': false,
};
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('CheckboxListTile demo')),
body: new ListView(
children: values.keys.map((String key) {
return new CheckboxListTile(
title: new Text(key),
value: values[key],
onChanged: (bool value) {
setState(() {
values[key] = value;
});
},
);
}).toList(),
),
);
}
}
void main() {
runApp(new MaterialApp(home: new Demo(), debugShowCheckedModeBanner: false));
}
I think it will work as you want. It also stores all selected checkbox value(s) into a List variable. so you please simply put this code in main.dart file and execute to check how it works.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Multi-Select & Unselect Checkbox in Flutter'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List _selecteCategorys = List();
Map<String, dynamic> _categories = {
"responseCode": "1",
"responseText": "List categories.",
"responseBody": [
{"category_id": "5", "category_name": "Barber"},
{"category_id": "3", "category_name": "Carpanter"},
{"category_id": "7", "category_name": "Cook"}
],
"responseTotalResult":
3 // Total result is 3 here becasue we have 3 categories in responseBody.
};
void _onCategorySelected(bool selected, category_id) {
if (selected == true) {
setState(() {
_selecteCategorys.add(category_id);
});
} else {
setState(() {
_selecteCategorys.remove(category_id);
});
}
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: ListView.builder(
itemCount: _categories['responseTotalResult'],
itemBuilder: (BuildContext context, int index) {
return CheckboxListTile(
value: _selecteCategorys
.contains(_categories['responseBody'][index]['category_id']),
onChanged: (bool selected) {
_onCategorySelected(selected,
_categories['responseBody'][index]['category_id']);
},
title: Text(_categories['responseBody'][index]['category_name']),
);
}),
);
}
}
use List contains returns bool.
here is example
List<int> selectedList = [];
List<Widget> mList; //you can't add equal
createMenuWidget(Course courses) {
for (int b = 0; b < courses.length; b++) {
Map cmap = courses[b];
mList.add(CheckboxListTile(
onChanged: (bool value){
setState(() {
if(value){
selectedList.add(cmap[course_id]);
}else{
selectedList.remove(cmap[course_id]);
}
});
},
value: selectedList.contains(cmap[course_id]),
title: new Text(cmap[course_name]),
));
}
}
The simple Way to Do this with Dynamic List of Data with CheckBox.
List<String>data= ["Mathew","Deon","Sara","Yeu"];
List<String> userChecked = [];
ListView.builder(
itemCount: data.length,
itemBuilder: (context, i) {
return ListTile(
title: Text(
data[i])
trailing:Checkbox(
value: userChecked.contains(data[i]),
onChanged: (val) {
_onSelected(val, data[i]);
},
)
//you can use checkboxlistTile too
);
})
// now we write the functionality to check and uncheck it!!
void _onSelected(bool selected, String dataName) {
if (selected == true) {
setState(() {
userChecked.add(dataName);
});
} else {
setState(() {
userChecked.remove(dataName);
});
}
}
And Its Done !!...
Enjoy Fluttering...
Give a thumbs up as it will work for you !! :P
Please use package grouped_buttons.
It support both checkbox and radio.
https://pub.dartlang.org/packages/grouped_buttons
CheckboxGroup(
labels: <String>[
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
],
disabled: [
"Wednesday",
"Friday"
],
onChange: (bool isChecked, String label, int index) => print("isChecked: $isChecked label: $label index: $index"),
onSelected: (List<String> checked) => print("checked: ${checked.toString()}"),
),
and full example of usage in here https://github.com/akshathjain/grouped_buttons/blob/master/example/lib/main.dart
and author's logic to implement
https://github.com/akshathjain/grouped_buttons/blob/master/lib/src/checkbox_group.dart
Basically, author use two List of Strings to control selected and unselect
void onChanged(bool isChecked, int i){
bool isAlreadyContained = _selected.contains(widget.labels.elementAt(i));
if(mounted){
setState(() {
if(!isChecked && isAlreadyContained){
_selected.remove(widget.labels.elementAt(i));
}else if(isChecked && !isAlreadyContained){
_selected.add(widget.labels.elementAt(i));
}
if(widget.onChange != null) widget.onChange(isChecked, widget.labels.elementAt(i), i);
if(widget.onSelected != null) widget.onSelected(_selected);
});
}
}
Screenshot (Null safe)
Code:
class _MyPageState extends State<MyPage> {
final Map<String, bool> _map = {};
int _count = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => setState(() => _map.addEntries([MapEntry('Checkbox #${++_count}', false)])),
),
body: ListView(
children: _map.keys
.map(
(key) => CheckboxListTile(
value: _map[key],
onChanged: (value) => setState(() => _map[key] = value!),
subtitle: Text(key),
),
)
.toList(),
),
);
}
}
Use chekboxListTile
Here is the sample code
#override
Widget build(BuildContext context) {
return Center(
child: CheckboxListTile(
title: Text('Check me'),
);
}
By the way, You can also add checkbox in ListView in Flutter. Apps sample is given below-
Main.dart
import 'package:flutter/material.dart';
import 'checkbox_in_listview_task-7.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.blue,
),
home: CheckBoxInListview(),
);
}
}
checkbox_in_listview_task.dart
import 'package:flutter/material.dart';
class CheckBoxInListview extends StatefulWidget {
#override
_CheckBoxInListviewState createState() => _CheckBoxInListviewState();
}
class _CheckBoxInListviewState extends State<CheckBoxInListview> {
bool _isChecked = true;
List<String> _texts = [
"InduceSmile.com," "Flutter.io",
"google.com",
"youtube.com",
"yahoo.com",
"gmail.com"
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("CheckBox in ListView Example"),
),
body: ListView(
padding: EdgeInsets.all(8.0),
children: _texts.map((text) => CheckboxListTile(
title: Text(text),
value: _isChecked,
onChanged: (val) {
setState(() {
_isChecked = val;
});
},
)).toList(),
),
);
}
}
And here is the output
here how you can do it
import 'package:flutter/material.dart';
class RegisterFragments extends StatefulWidget {
RegisterFragments({Key key, this.step}) : super(key: key);
final int step;
_RegisterFragmentsState createState() => _RegisterFragmentsState();
}
class _RegisterFragmentsState extends State<RegisterFragments> {
Map<String, bool> values = {"abc": false, "def": true, "ghi": false};
List<String> _do = ['One', 'Two', 'Free', 'Four'];
String _dropdownValue = 'One';
#override
Widget build(BuildContext context) {
switch (widget.step) {
case 0:
return buildDo();
break;
case 1:
return Container(
child: ListView.builder(
shrinkWrap: true,
itemCount: values.length,
itemBuilder: (BuildContext context, int index) {
switch (widget.step) {
case 0:
return buildDo();
break;
case 1:
return buildService(context, index);
break;
default:
return Container();
break;
}
},
),
);
break;
default:
return Container();
break;
}
}
Widget buildService(BuildContext context, int index) {
String _key = values.keys.elementAt(index);
return Container(
child: Card(
child: CheckboxListTile(
title: Text(_key),
onChanged: (bool value) {
setState(() {
values[_key] = value;
});
},
value: values[_key],
),
),
);
}
Widget buildDo() {
return DropdownButton<String>(
isExpanded: true,
hint: Text("Service"),
items: _do.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
this._dropdownValue = newValue;
});
},
value: _dropdownValue,
);
}
}
In case you are using the CheckBoxGroup or anything similar AND are inside a slider, do not forget to put it in a StatefulBuilder:
return StatefulBuilder(// StatefulBuilder
builder: (context, setState) {
return CheckboxGroup(
orientation: GroupedButtonsOrientation.HORIZONTAL,
margin: const EdgeInsets.only(left: 12.0),
onSelected: (List selected) => setState(() {
_checked = selected;
}),
labels: teamWorkoutDays,
checked: _checked,
itemBuilder: (Checkbox cb, Text txt, int i) {
return Column(
children: <Widget>[
Icon(Icons.polymer),
cb,
txt,
],
);
},
);
});