在视图层的使用 WillPopScope 做根组件
import 'package:flutter/material.dart';
class HomeView extends GetView<HomeController> {
HomeView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Obx((){
return WillPopScope(
onWillPop: ()async{
/* 判断两秒内点击两次返回按钮则退出APP */
if(controller.lastPopTime.value == null || DateTime.now().difference(controller.lastPopTime.value) > Duration(seconds: 2)){
Fluttertoast.showToast(
msg: "在按一次退出应用",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Color.fromARGB(57, 0, 0, 0),
textColor: Colors.white,
fontSize: 16.0
);
controller.setLastPopTime();
}else{
/* 退出app */
await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
}
return false;
},
child:Scaffold(...)
)
})
}
}
在 controller 组件中设置时间
/* 监听再按一次退出APP */
var lastPopTime = DateTime.now().obs;
/* 确认退出APP */
setLastPopTime(){
lastPopTime.value = DateTime.now();
update();
}