flutter返回PopScope

本文最后更新于 2024年8月27日 下午

PopScope 物理按键,返回退出应用程序

判断是否连续点击返回按键,android 对应的实体返回按钮或者虚拟返回按钮,使用需要将 PopScope 写在页面的最顶层(这点注意📢)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 连续返回,退出应用程序
DateTime? currentBackPressTime;
bool closeOnConfirm() {
DateTime now = DateTime.now();
// 物理键,两次间隔大于4秒, 退出请求无效
if (currentBackPressTime == null ||
now.difference(currentBackPressTime!) > const Duration(seconds: 4)) {
currentBackPressTime = now;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
behavior: SnackBarBehavior.floating,
content: Center(child: Text('再次按下以关闭应用程序')),
duration: Duration(seconds: 4),
),
);
return false;
}
// 清除时间戳
currentBackPressTime = null;
return true;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 配置 PopScope
return PopScope(
// 关闭系统返回
canPop: false,
onPopInvoked: (didPop) async {
if (didPop) {
return;
}
if (closeOnConfirm()) {
// 退出应用程序,关闭app
SystemNavigator.pop();
}
},
child: Scaffold(
appBar: AppBar(
title: const Text("手机号快捷登录",
style: TextStyle(
color: fontColor,
fontWeight: appBarTitleFontWeight,
fontSize: textTitleSize)),
),
body: const Center(
child: Text("手机号快捷登录"),
),
));

flutter返回PopScope
https://dev.dgdream.online/2024/08/27/flutter之PopScope/
作者
执念
发布于
2024年8月27日
更新于
2024年8月27日
许可协议