Flutter: How do I pop dialog as well as current page?

Issue

Below is the code.

  1. Navigation to Login page, from Home page
    ElevatedButton(
              onPressed: () => Navigator.of(context, rootNavigator: true)
                  .push(MaterialPageRoute(
                fullscreenDialog: true,
                builder: (context) => UserLoginPage(),
              )),
              child: Text('Login to continue'),
            ),

Inside Login page:

BlocConsumer<UserAuthCubit, UserAuthState>(
            listener: (context, state) {
              if (state is UserAuthorized) {
                Navigator.of(context, rootNavigator: true).pop();
              }
              if (state is UserAuthWaiting) {
                showModalBottomSheet(
                    useRootNavigator: true,
                    isDismissible: false,
                    context: context,
                    builder: (context) {
                      return WillPopScope(
                        onWillPop: () async => false,
                        child: Center(
                          child: Text(state.msg),
                        ),
                      );
                    });
                dialog = true;
              } else {
                if (dialog) {
                  Navigator.of(context, rootNavigator: true).pop();
                  dialog = false;
                }
              }
            },
            builder: (context, state) { // some widget code... }

When the state is UserAuthorized, I want to pop the dialog as well as the LoginPage, so as to return to the last page i.e. Home page. However, with the code above, sometimes, it works, and on another time, the Home page is also popped out.
I tried, with/without rootNavigator set to true, but couldn’t achieve my objective.

Please help me understand what I’m missing here.

I have checked the answer here How to dismiss flutter dialog?
.

Solution

You can simply use

Navigator.popUntil(context, (route) {
            return count++ == 2;
          });

UPDATE:

If you don’t know how many page you should pop then you should use

Navigator.push(context, MaterialPageRoute(builder: (context)=>YourMaterialClassName(), settings: RouteSettings(name: "nameOfYourClass")));

while you push your material class.

then in the time of poping up use

Navigator.popUntil(context, (route) => route.settings.name == "nameOfYourClass");

Answered By – Tipu Sultan

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *