So I have a ListView with Checkboxes
bool checked = false;
ListView.builder(
itemCount: logs!.length,
itemBuilder: (context, index) {
Log log = logs[index];
return ExpansionTile(
title:
Checkbox(
value: checked,
onChanged: (curValue) {
checked = curValue;
setState(() {});
}),
)
],
)
},
);
The problem is that when I check one Box in the List, all values are changed, because the variable is global & therefore the same boolean is appended to all checkboxes.
When I pack the boolean inside the ListView, I cant click on the Checkbox at all -> because of the setState the value is always reseted & no change appears
So what can I do to make all Checkboxes clickable without influencing the click state of the other ones?
CodePudding user response:
Since you have only 1 variable to check the state of the checkbox, all other checkbox widgets will also depend on this checked variable.
You have to define for every checkbox a own "checked" variable, you could add a checked variable to the Log class and then query and set it each time.
Checkbox(
value: logs[index].checked,
onChanged: (curValue) {
logs[index].checked = curValue;
setState(() {});
},
),
CodePudding user response:
The issue is here using single variable for all items. You can use a List for selected item
List<Log> selectedLogs = [];
Checkbox(
value: selectedLogs.contains(log),
onChanged: (curValue) {
if(selectedLogs.contains(log)){
selectedLogs.remove(log);
}else {
selectedLogs.add(log);
}
setState(() {});
}),
)