How to dismiss AlertDialog after Navigator.push?

Viewed 803

I am call Navigator.push() after user press button on AlertDialog. But when user press button AlertDialog remain open and on top of new page.

How to dismiss AlertDialog after user press button?

Future<void> _showMyDialog() async {
          return showDialog<void>(
            context: context,
            barrierDismissible: false, // user must tap button!
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text('AlertDialog Title'),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: <Widget>[
                      Text('This is a demo alert dialog.'),
                      Text('Would you like to approve of this message?'),
                    ],
                  ),
                ),
                actions: <Widget>[
                  FlatButton(
                    child: Text('Approve'),
                    onPressed: () async {

                       await Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => Page()),
                      );


                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        }

        await _showMyDialog();
1 Answers

The comment saying to call pop is probably the easiest way to do this.

Another thing to consider next is if you want them to be able to stay on the same page. Here is a way to do both of these if you get beyond the => NewPage() style of navigation on your app. It's more commonly used for Drawers, of course.

Happy coding!


onTap: () {
  newRouteName = "/form_check";
  // if the current route is the exact location we're at (first on the stack), mark that
  Navigator.popUntil(context, (route) {
    if (route.settings.name == newRouteName) {
      isNewRouteSameAsCurrent = true;
    } else {
      isNewRouteSameAsCurrent = false;
    }
    return true;
  });
  // if it isn't, go to the new route
  if (!isNewRouteSameAsCurrent) {
    Navigator.pushNamed(context, newRouteName);
  }
  // again if it is, just pop the drawer/dialog away
  else {
    Navigator.pop(context);
  }
}
Related