当用户在某一个时间段内点击两次时,才会认为用户是要退出(而非误触)。Flutter中可以通过WillPopScope来实现返回按钮拦截,
onWillPop是一个回调函数,当用户点击返回按钮时被调用(包括导航返回按钮及Android物理返回按钮)。该回调需要返回一个Future对象,如果返回的Future最终值为false时,则当前路由不出栈(不会返回);最终值为true时,当前路由出栈退出。
示例:
当用户在1秒内点击两次返回按钮时,则退出;如果间隔超过1秒则不退出,并重新记时。
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class StudyWillPopScope extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return StudyWillPopScopeState();
}
}
class StudyWillPopScopeState extends State<StudyWillPopScope>{
DateTime? lastPressTime;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("连续点击"),
),
body: Container(
child: WillPopScope(
onWillPop: () async {
if(lastPressTime == null ||DateTime.now().difference(lastPressTime!) > Duration(seconds: 1)){
//间隔时间大于1秒 则重新赋值
lastPressTime = DateTime.now();
Fluttertoast.showToast(msg: "再次点击退出",toastLength: Toast.LENGTH_SHORT);
return false;
}
return true;
},
child: Text("1秒内连续按两次返回键退出"),
),
),
);
}
}
效果
其中引入了fluttertoast库
1,依赖fluttertoast: ^8.0.7
2,import ‘package:fluttertoast/fluttertoast.dart’;
3,Fluttertoast.showToast(msg: “再次点击退出”,toastLength: Toast.LENGTH_SHORT);