Show alert dialog on app main screen load automatically

4,357 views
Skip to first unread message

Rajeev Mishra

unread,
Sep 6, 2018, 3:32:18 AM9/6/18
to Flutter Dev

I want to show alert dialog based on a condition. Not based on user interaction such as button press event.

If a flag is set in app state data alert dialog is shown otherwise its not.

Below is the sample alert dialog which I want to show

  void _showDialog() {
    // flutter defined function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Alert Dialog title"),
          content: new Text("Alert Dialog body"),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("Close"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

I tried to call that method inside main screen widget's build method but it gives me error -

 The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
E/flutter ( 3667): #0      Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:1179:9)
E/flutter ( 3667): #1      Navigator.of (package:flutter/src/widgets/navigator.dart:1186:6)
E/flutter ( 3667): #2      showDialog (package:flutter/src/material/dialog.dart:642:20)

Problem is I don't know from where I should call that _showDialog method?



I have asked a question as well on stack overflow
https://stackoverflow.com/questions/52164369/show-alert-dialog-on-app-main-screen-load-automatically

Matt Carroll

unread,
Sep 6, 2018, 4:40:55 PM9/6/18
to rajeev...@gmail.com, Flutter Dev
Hi Rajeev,

Do you definitely have a Navigator higher up in your UI hierarchy?  It looks like you're calling the showDialog() method from within a State Object, is that right?  If so, can you share the Widget hierarchy above that State?

The specific error you're receiving is because Flutter is looking for a Navigator to use for the dialog but it can't find one.

--
You received this message because you are subscribed to the Google Groups "Flutter Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages