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

别等时光非礼了梦想. 提交于 2021-01-29 19:07:50

问题


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? .


回答1:


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");



回答2:


I suggest after the dialog return true, instead of using Navigator.of(context).pop(). You can try use Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => HomePage())). By doing so you replace the LoginPage with HomePage



来源:https://stackoverflow.com/questions/63479766/flutter-how-do-i-pop-dialog-as-well-as-current-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!