Search code examples
fluttercheckboxlist

How to make checklist from a list of options in flutter?


Sample Data:

  var electricianmulti = [
  new Multimodel(
      question: "What services are you looking for?",
      options: ["Complete wiring", "switches", "water motor", "MCB & fuse"],

  new Multimodel(
      question: "What time of the day do you prefer?",
      options: ["Early Morning", "Morning", "Afternoon", "Evening"],];
      

I am making checkboxes from listview.generate as follows-

children: <Widget>[
                  ...List.generate(
                      electricianmulti[i].options.length,
                      (index) => Container(
                          padding: EdgeInsets.all(5),
                          margin: EdgeInsets.all(10),
                          child: CheckboxListTile(
                            // controlAffinity: ListTileControlAffinity.leading,
                            title: new Text(
                              electricianmulti[i].options[index].toString(),
                              style: optionstxt,
                            ),
                            value:isselected,
                            activeColor: Colors.blue,
                            checkColor: Colors.white,
                            onChanged: (bool value) {
                              setState(() {
                               isselected=value
                              });
                            },

This code works like if i click on any of the box all get checked. I tried making a array of bool and update it based on 'i' but it also doesnt seem to work. What am i doing wrong here?


Solution

  • value: isselected
    

    is taking a single boolean value and assigning it to all checkboxes. Change isselected to a list of boolean and then use

    value: isselected[i];
    

    Also in setState, use

    isselected[i] = value;
    

    Make sure the length of the isselected is equal to the number of checkboxes.