導(dǎo)航返回?cái)r截WillPopScope
為了避免用戶誤觸返回按鈕而導(dǎo)致APP退出,在很多APP中都攔截了用戶點(diǎn)擊返回鍵的按鈕,當(dāng)用戶在某一個(gè)時(shí)間段內(nèi)點(diǎn)擊兩次時(shí),才會(huì)認(rèn)為用戶是要退出(而非誤觸)。Flutter中可以通過(guò)WillPopScope來(lái)實(shí)現(xiàn)返回按鈕攔截,我們看看WillPopScope的默認(rèn)構(gòu)造函數(shù):
const WillPopScope({
...
@required WillPopCallback onWillPop,
@required Widget child
})
onWillPop是一個(gè)回調(diào)函數(shù),當(dāng)用戶點(diǎn)擊返回按鈕時(shí)調(diào)用(包括導(dǎo)航返回按鈕及Android物理返回按鈕),該回調(diào)需要返回一個(gè)Future對(duì)象,如果返回的Future最終值為false時(shí),則當(dāng)前路由不出棧(不會(huì)返回),最終值為true時(shí),當(dāng)前路由出棧退出。我們需要提供這個(gè)回調(diào)來(lái)決定是否退出。
示例
為了防止用戶誤觸返回鍵退出,我們攔截返回事件,當(dāng)用戶在1秒內(nèi)點(diǎn)擊兩次返回按鈕時(shí),則退出,如果間隔超過(guò)1秒則不退出,并重新記時(shí)。代碼如下:
import 'package:flutter/material.dart';
class WillPopScopeTestRoute extends StatefulWidget {
@override
WillPopScopeTestRouteState createState() {
return new WillPopScopeTestRouteState();
}
}
class WillPopScopeTestRouteState extends State<WillPopScopeTestRoute> {
DateTime _lastPressedAt; //上次點(diǎn)擊時(shí)間
@override
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: () async {
if (_lastPressedAt == null ||
DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1)) {
//兩次點(diǎn)擊間隔超過(guò)1秒則重新計(jì)時(shí)
_lastPressedAt = DateTime.now();
return false;
}
return true;
},
child: Container(
alignment: Alignment.center,
child: Text("1秒內(nèi)連續(xù)按兩次返回鍵退出"),
)
);
}
}