How to navigate from Error dialog with flutter

Viewed 1590

I'm using Firebase with Flutter. After I retrieve documents as a contents list, I don't know how to handling screen. The code is in StreamBuilder. I would like to show dialog at first, and after push dialog OK button, navigate the other next screen.

How ever following code does not navigate next screen.

final List<DocumentSnapshot> contents = snapshot.data.documents;

if (contents.length == 0) {
  try {
    print('NO DATA FOR THIS USER. ${contents.length}');
    showDialog(
        context: context,
        builder: (_) {
          return AlertDialog(
            title: Text('Error'),
            content: Text('Please Register First.'),
            actions: <Widget>[
              FlatButton(
                child: Text('OK'),
                onPressed: () {
                   Navigator.push(context,
                     MaterialPageRoute(builder: (context) => NextPage()));
                    //Navigator.pop(context);
                },
              ),
            ],
          );
        });
  } catch (e) {
    return Container();
  }
}

If I don't return Container, Error screen show up.

2 Answers

According to me , You should remove the dialogue from the navigator stack and then do materialPageRoute. So this would be the code.

And builder parameter of showDialog requires a parameter of type

Widget Function(BuildContext)

hence , instead of underscore, try passing "context" as argument , as shown below.

final List<DocumentSnapshot> contents = snapshot.data.documents;

if (contents.length == 0) {
  try {
    print('NO DATA FOR THIS USER. ${contents.length}');
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Error'),
            content: Text('Please Register First.'),
            actions: <Widget>[
              FlatButton(
                child: Text('OK'),
                onPressed: () {
                   Navigator.pop(context);
                   Navigator.push(context,
                     MaterialPageRoute(builder: (context) => NextPage()));
                    //Navigator.pop(context);
                },
              ),
            ],
          );
        });
  } catch (e) {
    return Container();
  }
}

I figured out. I should have insert this code before the screen show up. I had implemented this code wrong place. It is hard to explain.

However it worked.

Related