Search code examples
flutterdartdialogflutter-layoutflutter-alertdialog

Get a Checkbox in an AlertDialog


I added an AlertDialog, in which a Checkbox is, but if I tap on the Checkbox, it doesn´t get a hook. I also added another Checkbox below the AlertDialog and this one gets a hook by clicking on it. I think it has something with setState() to do, but I don´t know. Does anybody knowes a solution? Thanks in advance

ListTile(
                title: Text("Test"),
                trailing: Icon(Icons.fitness_center),
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text("Test"),
                        content: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Checkbox(
                                  value: checkBoxValueTheraband,
                                  onChanged: (bool value) {
                                    setState(() {
                                      checkBoxValueTheraband = value;
                                      exerciseChooser();
                                    });
                                  },
                                ),
                                Text("Theraband"),
                              ],
                            ),),);});})

Solution

  • The setState you are using in the showDialog is not "owned" by it, which means it will not rebuild anything in it and actually update the state of the parent that "owns" it. Instead, you give it its own StatefulBuilder that has its own StateSetter setState as a parameter. Now when setState is used it will invoke the builder and change the state of anything in this widget.

     content: StatefulBuilder(
                 builder: (BuildContext context, StateSetter setState) {
                    return  Column(
                              children: <Widget>[
                                Row(
                                  children: <Widget>[
                                    Checkbox(
                                      value: checkBoxValueTheraband,
                                      onChanged: (bool value) {
                                        setState(() { 
                                       checkBoxValueTheraband = value;
                                          exerciseChooser();
                                        });
                                      },
                                    ),
                                    Text("Theraband"),
    
                                  ]),
    
                                ]);
    
                       }
                   )