如需轉(zhuǎn)載,請(qǐng)注明出處:Flutter學(xué)習(xí)筆記(26)--返回?cái)r截WillPopScope,實(shí)現(xiàn)1秒內(nèi)點(diǎn)擊兩次返回按鈕退出程序在實(shí)際開(kāi)發(fā)中,為了防止用戶(hù)誤觸返回按鈕導(dǎo)致程序退出,通常會(huì)設(shè)置為在1秒內(nèi)連續(xù)點(diǎn)擊兩次才會(huì)退出應(yīng)用程序。Android中一般的處理方式是在onKeyDown方法內(nèi)做計(jì)時(shí)處理,當(dāng)keyCode == KeyEvent.KEYCODE_BACK 且 兩次點(diǎn)擊返回按鈕間隔時(shí)間小于1秒則退出應(yīng)用程序,在Flutter中可以通過(guò)WillPopScope來(lái)實(shí)現(xiàn)攔截返回按鈕,并且在其內(nèi)部做計(jì)時(shí)處理。 WillPopScope構(gòu)造函數(shù):
const WillPopScope({ Key key, @required this.child, @required this.onWillPop,//回調(diào)函數(shù),當(dāng)用戶(hù)點(diǎn)擊返回按鈕時(shí)調(diào)用 })
onWillPop是一個(gè)回調(diào)函數(shù),當(dāng)用戶(hù)點(diǎn)擊返回按鈕時(shí)被調(diào)用,這里的返回按鈕包括導(dǎo)航返回按鈕及物理返回按鈕,該回調(diào)需要返回一個(gè)Future對(duì)象,如果返回的Future最終值為false時(shí),當(dāng)前路由不出棧(不返回),如果返回為true時(shí),則當(dāng)前路由出棧退出。 下面的Demo是實(shí)現(xiàn)了在1秒內(nèi)連續(xù)點(diǎn)擊兩次退出應(yīng)用程序的功能。想要做到計(jì)時(shí)處理,就需要獲取到當(dāng)前時(shí)間,計(jì)算兩次點(diǎn)擊之間的時(shí)間差 獲取當(dāng)前時(shí)間: DateTime.now() 計(jì)算當(dāng)前時(shí)間和上次點(diǎn)擊的時(shí)間差: DateTime.now().difference(_lastPressedAt) 時(shí)間差判斷(是否大于1秒): DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1)
完整Demo示例:
import 'package:flutter/material.dart'; void main() => runApp(DemoApp()); class DemoApp extends StatefulWidget { @override State<StatefulWidget> createState() { return new DemoAppState(); } } class DemoAppState extends State<DemoApp> { DateTime _lastPressedAt;//上次點(diǎn)擊的時(shí)間 @override Widget build(BuildContext context) { return new MaterialApp( title: 'WillPopScope Demo', home: new Scaffold( appBar: new AppBar( title: new Text('WillPopScope Demo'), ), body: new WillPopScope( child: new Center( child: new Text('WillPopScope'), ), onWillPop: () async{ if(_lastPressedAt == null || (DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1))){ //兩次點(diǎn)擊間隔超過(guò)1秒,重新計(jì)時(shí) _lastPressedAt = DateTime.now(); print(_lastPressedAt); return false; } return true; } ), ), ); } }
|
|
來(lái)自: 悅光陰 > 《待分類(lèi)》