Flutter双击退出应用

WillPopScope 注册一个回调 onWillPop 用来自定义用户对路由的操作

(1)自定义双击退出回调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int _lastClickTime = 0;

Future<bool> _doubleClickExit() {
int nowTime = new DateTime.now().microsecondsSinceEpoch;
if (_lastClickTime != 0 && nowTime - _lastClickTime > 1500) {
return new Future.value(true);
} else {
print('Click again to exist!');
_lastClickTime = new DateTime.now().microsecondsSinceEpoch;
new Future.delayed(const Duration(milliseconds: 1500), () {
_lastClickTime = 0;
});
return new Future.value(false);
}
}

(2)将事先创建好的子节点 _getBody() 嵌套在 WillPopScope 中

1
2
3
4
5
6
7
8
9
10
11
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('Home'),),
body: WillPopScope(
onWillPop: _doubleClickExit,
child: _getBody(),
)
);
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :