KevinM
KevinM

Reputation: 1807

How to open a Flutter dialog no matter where the user is within the app

I'm working on a Flutter project where I need the ability to show the user a dialog no matter where they happen to be within the app. Currently I'm executing the showDialog() function in the root level widget that main() kicks off.
That widget implements WidgetsBindingObserver so that I can listen for when the app moves from the background to the foreground via the didChangeAppLifecycleState() function. Anytime this happens I make a request to a service provider and depending on the results I need to show a dialog.
The users will be navigated to some other route anytime this happens, and that's where I seem to be running into trouble. Below is the stripped down function that performs the API call and subsequent showDialog() attempt. But nothing ever happens. I tried wrapping it in a 2 second timer thinking maybe it was an issue of the app just coming back into the foreground, but that didn't make a difference.

void _fetchSuperAwesomeStuff() {
  final apiCaller = new SuperAwesomeStuffAPI();
  apiCaller.fetchSuperAwesomeStuff().then((List<SuperAwesomeStuff> superAwesomeStuffs) {
    if (superAwesomeStuffs != null && superAwesomeStuffs.length > 0) {
      SuperAwesomeStuff superAwesomeStuff = superAwesomeStuffs[0];

      // .... DOING STUFF WITH THIS SUPER AWESOME STUFF .... //

      // NEED TO SHOW A DIALOG.
      showDialog(
        context: context,
        builder: (_) => new AlertDialog(
          title: Text('Test Title'),
          actions: <Widget>[
            new FlatButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: new Text('Close'),
            ),
          ],
        ),
      );
    }
  });
}

Any help with this would be greatly appreciated, thank you!

Upvotes: 0

Views: 1410

Answers (1)

chemamolins
chemamolins

Reputation: 20558

You need to pass a BuildContext for the context variable, and that context needs to be mounted (the corresponding element) in the tree when you make the call.

Alternatively, you could send a message/stream from your superawesome logic to any part of the app that has a context and listens to the stream. From here you could call the dialog.

Upvotes: 1

Related Questions