24 WillPopScope 的使用
1.源代码
import 'package:flutter/material.dart';
void main () => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
DateTime lastTime;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("点两次返回键退出"),),
body: Builder(builder: (context)=>WillPopScope(
onWillPop: () async {
if (lastTime == null || DateTime.now().difference(lastTime) >
Duration(seconds: 1)) {
lastTime = DateTime.now();
Scaffold.of(context).showSnackBar(SnackBar(content: Text("再点一次退出!")));
return false;
}
return true;
},
child: Container(
alignment: Alignment.center,
child: Text("1秒内连续按两次返回键退出"),
)
))
)
);
}
}
2.解释源代码
import 'package:flutter/material.dart';
void main () => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
DateTime lastTime;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("点两次返回键退出"),),
body: Builder(builder: (context)=>WillPopScope(
onWillPop: () async {
if (lastTime == null || DateTime.now().difference(lastTime) >
Duration(seconds: 1)) {
lastTime = DateTime.now();
Scaffold.of(context).showSnackBar(SnackBar(content: Text("再点一次退出!")));
return false;
}
return true;
},
child: Container(
alignment: Alignment.center,
child: Text("1秒内连续按两次返回键退出"),
)
))
)
);
}
}
3.效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0807f18d6fee94ed07d2c1650f4906ad.png)