flutterdartcheckboxflutter-dialog

How to change boolean value from a Dialog?


I need to change a Boolean value from a Dialog. It works if I have my Checkbox on my page, but not when I try it in a Dialog.

How can I get the value of ìsselected1 from my Dialog to my page?

Here is my Dialog:

IconButton(onPressed: () {
                showDialog(context: context, builder: (ctx) {
                  return StatefulBuilder(
                    builder: (context, setState) {
                      return Dialog(
                        child: SizedBox(
                          height: 200,
                          width: 100,
                          child: Column(
                            children: [
                           
                              Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Row(
                                  children: [
                                    Text('Test'),
                                    Checkbox(value: isselected1, onChanged: (value) {
                                      setState(() {
                                     
                                        isselected1 = value!;
                                      });
                                    }),
                                    
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      );
                    },
                  );
                });

              }, icon: Icon(Icons.add))
            ],
          ),

Solution

  • You can change the setState of StatefulBuilder to something else. It will clear the concept.

    return StatefulBuilder(
      builder: (context, setStateSB) { //renamed to setStateSB
        return Dialog(
          child: SizedBox(
            height: 200,
            width: 100,
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    children: [
                      Text('Test'),
                      Checkbox(value: isselected1, onChanged: (value) {
                        isselected1 = value!;
                          setStateSB(() { }); //update dialog UI
                        setState(() {}); // update state  class UI
                      }),
                      
                    ],
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
    

    Also you can call setState after closing the dialog, or get data from dialog and then call setState, An easy way will be

     () async {
      await showDialog(....);
      setState((){});
    

    But I prefer receiving data and then update UI based on it.