How to confirm app exit when appbar back button is pressed

大兔子大兔子 提交于 2021-02-11 12:22:01

问题


I want to confirm exiting the app when the back button on the appbar is pressed.

 appBar: AppBar(
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
            ),
            onPressed: () {
              showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    title: Text('Save and Exit?'),
                    content: Text('are you sure you want to save and exit?'),
                    actions: [
                      FlatButton(
                        onPressed: () => Navigator.pop(context, false),
                        child: Text('No'),
                      ),
                      FlatButton(
                        onPressed: () => Navigator.pop(context, true),
                        child: Text('Yes'),
                      ),
                    ],
                  );
                },
              );
              // Navigator.pop(context);
            },
          ),

I tried this but didn't work. I have found some answers on how to do it when the system back button is pressed using WillPopScope but none of them work in my case.

Help me out


回答1:


You can check it with Navigator.canPop(context) i guess. It will return true or false. in onPressed you can check it, if it's true you can do Navigator.pop(context) otherwise call showDialog.

there is link of doc https://api.flutter.dev/flutter/widgets/Navigator/canPop.html



来源:https://stackoverflow.com/questions/65673353/how-to-confirm-app-exit-when-appbar-back-button-is-pressed

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