导航返回拦截(WillPopScope),为了防止用户点击返回退出
DateTime lastPopTime;
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(
appBar: AppBar(
title: Text('点击两次返回退出APP',style: TextStyle(color: Colors.white,fontSize: 20),),
),
body: Center(
child: Text('点击两次返回退出APP'),
),
),
onWillPop: () async{
// 点击返回键的操作
if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: 2)){
lastPopTime = DateTime.now();
Toast.toast(context,msg: '再按一次退出');
}else{
lastPopTime = DateTime.now();
// 退出app
await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
}
},
);
}
{Future<bool> Function() onWillPop} 在用户点击返回键时,将会调用这个方法
Called to veto attempts by the user to dismiss the enclosing [ModalRoute].
If the callback returns a Future that resolves to false, the enclosing route will not be popped.