这个问题可能是重复的,但我找不到解决方案。我的应用场景和几乎应用一样。我的第一个屏幕是闪屏并保持两秒钟,这里检查登录 session ,在这种情况下屏幕会像这样更改,下面的代码在 initState()
中运行。
_checkPreference() async {
PreferencesConnector myprefs= PreferencesConnector();
id=await myprefs.readString('merchantid');
if(id==null||id==''){
Future.delayed(
const Duration(seconds: 2),
() => Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Login(),settings: RouteSettings(name: '/login')),
));
}else{
Future.delayed(
const Duration(seconds: 2),
() => Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => DashBoard()),
));
}
}
如果 session 返回 false,那么它将转到 login
屏幕,在登录屏幕中我的 scaffold
在里面 WillPopScope
小部件和那个类是 stateful
类
return WillPopScope(
onWillPop: () {
if (Navigator.canPop(context)) {
//Navigator.pop(context);
Navigator.of(context).pop();
} else {
SystemNavigator.pop();
}
},
child:Scaffold(
body: Stack(
children: <Widget>[
如果 LoginApi 返回 true 则它移动到 dashboard
像这样
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => DashBoard(),
settings: RouteSettings(name: '/dashboard')),
);
这里一切正常,当用户已经登录时,我们在启动后到达仪表板,但是有一个 logOut
当用户按下 logout
时我仪表板上的按钮然后出现一个对话框,要求注销 - 如果我从对话框按钮中按是,就像这样
onPressed:(){
clearSession();
// Navigator.of(context).popUntil(ModalRoute.());
// Navigator.of(context).popUntil('/login', (Route<dynamic> route) => false);
// Navigator.popUntil(context, ModalRoute.withName("/login"));
// Navigator.of(context).pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Login()),);
},
按下注销后,它到达登录屏幕,当用户从设备返回登录屏幕时,我无法关闭应用程序,但它重定向到仪表板,然后我按下,然后应用程序关闭。强>
最佳答案
您需要做的是在进入login()
屏幕之前先清除所有路径。
试试这个:
onPressed:(){
clearSession();
//Navigator.popUntil(context, ModalRoute.withName('/'));
Navigator.pop(context,true);// It worked for me instead of above line
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Login()),);
},
关于android - 在 flutter 中关闭设备后退按钮上的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54827477/