'Cannot Select Checkbox List Tile Flutter
I've created a map of values to make checkboxes. The map consists of String and bools and when the value of the bool is changed, the check box value should change.
EDIT 1:
My ListView Checkbox
CheckboxListTile(
title: new Text(
key,
style: textHeaderStyle,
),
value: _selectedOrders.contains(undeliveryOrders[key]),
activeColor: Colors.pink,
checkColor: Colors.white,
onChanged: (bool value) {
setState(() {
if(value){
_selectedOrders.add(undeliveryOrders[key]);
undeliveryOrders[key] = value;
}else{
setState(() {
_selectedOrders.remove(undeliveryOrders[key]);
});
}
});
},
)
Creating the Map:
void _formatOrders(availableOrders) {
for (int i = 0; i < availableOrders.length; i++) {
var tempOrder = '${availableOrders[i].customer.uniqueInfo.name} , ${availableOrders[i].address}';
undeliveryOrders['$tempOrder'] = false;
}
print('$undeliveryOrders');
print('$numbers');
}
Selected Order Method
var _selectedOrders = [];
getItems() {
undeliveryOrders.forEach((key, value) {
if (value == false) {
_selectedOrders.add(key);
}
});
print(_selectedOrders);
_selectedOrders.clear();
}
Solution 1:[1]
In my case, the setState()
is not responding, try to use StatefulBuilder()
.
For Example:
...
bool isSelected = false;
StatefulBuilder(
builder: (context, _setState) {
return ListView(
children: [
CheckboxListTile(
value: isSelected,
onChanged: (bool? value) {
_setState(() => isSelected = value);
},
),
],
);
},
);
...
Solution 2:[2]
I think you might be over complicating things every value does not have to be mapped to a boolean the way I do it is I add the value that gets checked to an array then check if that item is in that array if it is its true if not its false. You just have to remember to remove the item if the checkbox is unchecked here is some sample code for you.
List<String> items = ['Item 1', 'Item 2', 'Item 3'];
List<String> isChecked = [];
//Initialized outside build
ListView(
children: <Widget>[
...items
.map(
(item) => CheckboxListTile(
subtitle: Text('This is a subtitle'),
secondary: Text('This is Secondary text'),
title: Text(item),
value: isChecked.contains(item),
onChanged: (bool value) {
if (value) {
setState(() {
isChecked.add(item);
});
} else {
setState(() {
isChecked.remove(item);
});
}
},
),
)
.toList()
],
),
Solution 3:[3]
You can try with this code bellow ?
onChanged: (bool value) {
setState(() {
undeliveryOrders[key] = value ?? false;
});
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | John Melody Me |
Solution 2 | wcyankees424 |
Solution 3 | dangngocduc |