簡介
Flutter中可以通過WillPopScope來實現返回按鈕攔截
onWillPop是一個WillPopScope的回調函數,當用戶點擊返回按鈕時被調用
WillPopScope必須包含child,否則會報錯
實現雙擊返退出APP
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return WillPopTest();
}
}
class WillPopTest extends State {
DateTime _lastTime;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
centerTitle: true,
title: Text(
'實現二次點擊退出',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
body: WillPopScope(
onWillPop: ()async{
if(_lastTime==null||DateTime.now().difference(_lastTime)>Duration(seconds: 1)){
_lastTime=DateTime.now();
Fluttertoast.showToast(msg: "再點擊一次退出app",
fontSize: 16,
backgroundColor: Colors.blue,
textColor: Colors.white
);
return false;
}
return true;
},
child: Container(
alignment: Alignment.center,
child: Text(
"1秒內連續按兩次返回鍵退出",
style: TextStyle(fontSize: 30),
),
),
),
),
);
}
}
運行效果