导航返回拦截(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.
该博客介绍了如何使用Flutter的WillPopScope widget来防止用户意外退出应用。通过设置一个时间间隔,只有当用户在短时间内连续两次点击返回按钮,才会真正退出应用。这为用户提供了一个确认退出的机制,增加了用户体验。
5022

被折叠的 条评论
为什么被折叠?



