1. 计算两个日期的时间差
DateTime.now().difference(_lastPressedAt!)
//使用 difference 方法,就能获取到所有时间单位的差值
其中,DateTime
的 difference 方法
返回的是一个 Duration 对象
。Duration
是用来表示 时间跨度(差值)
的类。
参考文章:
Flutter 计算两个日期的时间差
小白不止如此 :(Dart)用法补充
2. 导航返回拦截: WillPopScope
DateTime? _lastPressedAt; //上次点击时间
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(
body: Container(
alignment: Alignment.center,
child: Text("2秒内连续按两次返回键退出"),
),
),
onWillPop: () async {
if (_lastPressedAt == null || DateTime.now().difference(_lastPressedAt!) > Duration(seconds: 2)) {
//两次点击间隔超过2秒则重新计时
_lastPressedAt = DateTime.now();
Fluttertoast.showToast(
msg: '再按一次退出!',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2,
backgroundColor: Colors.black87,
textColor: Colors.white,
);
return false;//当前路由不出栈(不会返回)
}
return true;//当前路由出栈退出
},
);
}