'How to handle multiple checkboxes from a Listview.builder?
I have a ListView.builder which returns a checkbox and its label. This listview will return a list of checkboxes and labels which will be displayed on the screen. Currently, I'm just creating a global variable isChecked and changing the value of the checkbox with onChanged callback and this value. But it changes the values of all the checkboxes present on the screen.
I need a way to handle each checkbox individually without modifying other checkbox values. And also keep a count of the ticked checkboxes. I'm using a checkboxtile widget for this.
Solution 1:[1]
As you have not shared any code, i assume you have a single variable isChecked. But you should have a list of isChecked so that you can store them separately.
List<bool> isChecked = List<bool>.generate(length, index => false);
ListView.builder(
itemCounter: length,
itemBuilder: (BuildContext context,int index){
return Checkboxtile (
title: 'label',
value: isChecked[index],
onChanged: (newValue) {
setState(() {
isChecked[index] = newValue;
});
},
);
}
To calculate the no. of the ticked checkBox:
int _checkedBox = 0;
for (int i = 0; i < isChecked.length; i++)
if (isChecked[i])
_checkedBox++;
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 |
