flutter 導(dǎo)航返回?cái)r截WillPopScope(防誤觸)

導(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ù)按兩次返回鍵退出"),
        )
    );
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容