Flutter: setState not updating UI after popping

Viewed 50

I have a flutter application where the variable is initialized outside of the build function. In the build I have :

onPressed: (BuildContext context) async {
   await showDialog(
      context: context,
      builder: (context) => Dialog(
         ...
         Navigator.pop()
      );
   ).then((_) => setState(() {
     print("Test is this prints");
   ));
   setState(){ flag = !flag }
}


The purpose of the setState is just so that the UI is updates after I close out of the dialog window. I have a util file that is makes some changes to the UI when I close out of the dialog, and I would like to see it reflected after I close out of the dialog.

For some reason, the UI is not changing even though setState should be rebuilding the widget since something changes.

When I do the .then(setState(){}), the console prints the print statement, but the UI is still not changing.

3 Answers

In which code or widget, you are using the flag variable.

If flag is not used in any of the widget then your UI will not be updated.

Remove multiple setState, just use one and also check usage of flag variable in your code.

.then((_) => setState(() {
     flag = !flag
     print("Test is this prints and updated flag value is $flag");
   ));

When rebuild by setState(), flag is also reset. So always flag is false.

Make it a variable inside the State class

   onPressed: (BuildContext context) async {
   await showDialog(
      context: context,
      builder: (context) => Dialog(
         ...
         Navigator.pop()
      );
   ).then((_) => setState(() {
     print("Test is this prints");
       flag = !flag
   ));
  
}
Related