Flutter 返回键监听,提示再按一次退出app
直接贴代码
@override
Widget build(BuildContext context) {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.dark,
child: MaterialApp(
debugShowCheckedModeBanner: false,
// theme: ThemeData(primarySwatch: Colors.red, primaryColor: Colors.blue),
home: WillPopScope(
child: Scaffold(
body: Tabs(),
),
onWillPop: () async {
// 点击返回键的操作
if (lastPopTime == null ||
DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
lastPopTime = DateTime.now();
Fluttertoast.showToast(
msg: '再按一次退出',
fontSize: 14,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
textColor: Colors.black,
);
} else {
lastPopTime = DateTime.now();
// 退出app
await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
}
},
),
// initialRoute: '/',
onGenerateRoute: onGenerateRoute,
),
);
}
使用 WillPopScope包裹住Scaffold,onWillPop是监控返回键方法,这边用到的Fluttertoast吐司弹框是引得第三方,如果有需要查看前面文章。