How to check single checkboxes in a listview builder flutter

Advertisements

How do I use checkbox correctly in a listview in flutter, with the below code once i check one of the boxes the all checkbox in the listview gets clicked instead of the single one i clicked.

ListView.builder(
                                shrinkWrap: true,
                                physics: const NeverScrollableScrollPhysics(),
                                itemCount: bool_.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return CheckboxListTile(
                                    value: values,
                                    title: Text(bool_[index].name),
                                    onChanged: (selected) {
                                      setState(() {
                                        values = selected!;
                                        isSelected(selected, bool_[index].name);
                                      });
                                    },
                                  );
                                }),

the isSelected function is working fine am able to get the name of the checkbox according to which was clicked the only issue is all the checkbox get checked and unchecked at the same time

>Solution :

You have to use unique value for single selection ,

dynamic? values;

value should be type of bool_[index].

                             ListView.builder(
                                shrinkWrap: true,
                                physics: const NeverScrollableScrollPhysics(),
                                itemCount: bool_.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return CheckboxListTile(
                                    value: values == bool_[index],
                                    title: Text(bool_[index].name),
                                    onChanged: (selected) {
                                      setState(() {
                                        if(values == bool_[index]){
                                           values = null;
                                        } else {
                                          values = bool_[index];
                                        }
                                        isSelected(selected, bool_[index].name);
                                      });
                                    },
                                  );
                                }),

If you want to allow multiple selection then you should have List<dynamic> values = [];, and value = values.contains(bool_[index]) and in onChanged, you have add or remove based on condition values.contains(bool_[index])

I hope this helps

Leave a ReplyCancel reply