Flutter – Open flutter dialog after navigation

flutter

I call Navigator pushReplacement to show a new view within my flutter app and want to immediately pop up a simple dialog to introduce the page to the user. (I want the user to be able to see the new view in the background)

If I call showDialog within the build method of a widget, and then subsequently return a widget (scaffold) from the build method I get errors stating that flutter is already drawing a widget. I expect I need to listen on a build complete event and then call showDialog.

Guidance on how to do that much appreciated.

Best Answer

You can call the dialog from inside 'initState()' dalaying its appearance after the first frame has been drawn.

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await showDialog<String>(
        context: context,
        builder: (BuildContext context) => new AlertDialog(
              title: new Text("title"),
              content: new Text("Message"),
              actions: <Widget>[
                new FlatButton(
                  child: new Text("OK"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ),
      );
    });
  }

The context variable is always available inside the State class. It points to the RenderObject of this widget. The problem is that in initState() the context is not yet created so you have to defer its usage after the first frame has been laid out. Then it is available.

Related Topic