Search code examples
fluttershowdialog

How to showDialog in FutureBuilder


In Flutter, I used FutureBuilder to display data from API. I would like to popup an error dialog when there's error.

However, it throws error when I called showDialog()

setState() or markNeedsBuild() called during build.

Here's my code

    return FutureBuilder(
      future: xxx,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          //DO SOMETHING

        } else if (snapshot.hasError) {
          //TODO: Show Error

          showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text("Error"),
                  content: Text("HAHAHA"),
                  actions: <Widget>[
                    FlatButton(
                      child: Text("No"),
                    ),
                    FlatButton(
                        child: Text("Yes")
                    ),
                  ],
                );
              }
          );

          return Container();

        } else {
          //DO SOMETHING
        }
      },

Please help to advise how could I showDialog in FutureBuilder.


Solution

  • We can not call setState, navigate or showDialog while build method is building widget. so, we can wait for a microsecond and meanwhile build method complete building widget, so we can show dialog.

    Create a method like below.

    showError() async {
        await Future.delayed(Duration(microseconds: 1));
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("Error"),
                content: Text("HAHAHA"),
                actions: <Widget>[
                  FlatButton(
                    child: Text("No"),
                  ),
                  FlatButton(child: Text("Yes")),
                ],
              );
            });
      }
    

    And call this method Where you want to show dialog.