Flutter showDialog popup after navigating to another screen

1.2k Views Asked by At

My application consists of two screens. The first screen runs a timer which calls a showDialog on its end. The dialog should appear only on the first screen.

But whenever I'm navigating to the second screen, and the timer from the first screen ends, then the dialog shows up.

The user should see the dialog only after getting back to the first screen.

How do I restrict a showDialog to appear only on the first screen?

enter image description here

The timer from the first screen:

StreamBuilder(
  stream: timerBloc.seconds,
  initialData: "-",
  builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
    if (snapshot.hasData) {
      if (snapshot.data == 0) {
        WidgetsBinding.instance!.addPostFrameCallback((_) {
          myDialog();
        });
      }
      return SizedBox();
    }
    return const SizedBox();
  },
)
1

There are 1 best solutions below

5
On

You can check if the Widget is mounted by checking

if(mounted){
 showDialog()
}

If this doesn't work, the easiest way would be to have a flag whether you are still on the screen where you want the dialog to appear :

// outside of build function
bool showDialog = true;
...
StreamBuilder(
  stream: timerBloc.seconds,
  initialData: "-",
  builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
    if (snapshot.hasData) {
      if (snapshot.data == 0) {
        WidgetsBinding.instance!.addPostFrameCallback((_) {
         if(showDialog){
          myDialog();
         }
        });
      }
      return SizedBox();
    }
    return const SizedBox();
  },
)

Of course you will need to change the variable when you navigate to your second screen

showDialog=false;
setState((){});
Navigator.push(secondScreen);