Flutter學習筆記(26)--返回攔截WillPopScope,實現1秒內點擊兩次返回按鈕退出程序


如需轉載,請注明出處:Flutter學習筆記(26)--返回攔截WillPopScope,實現1秒內點擊兩次返回按鈕退出程序

在實際開發中,為了防止用戶誤觸返回按鈕導致程序退出,通常會設置為在1秒內連續點擊兩次才會退出應用程序。Android中一般的處理方式是在onKeyDown方法內做計時處理,當keyCode == KeyEvent.KEYCODE_BACK 且 兩次點擊返回按鈕間隔時間小於1秒則退出應用程序,在Flutter中可以通過WillPopScope來實現攔截返回按鈕,並且在其內部做計時處理。

WillPopScope構造函數:

 

const WillPopScope({
  Key key,
  @required this.child,
  @required this.onWillPop,//回調函數,當用戶點擊返回按鈕時調用
})

 

onWillPop是一個回調函數,當用戶點擊返回按鈕時被調用,這里的返回按鈕包括導航返回按鈕及物理返回按鈕,該回調需要返回一個Future對象,如果返回的Future最終值為false時,當前路由不出棧(不返回),如果返回為true時,則當前路由出棧退出。

下面的Demo是實現了在1秒內連續點擊兩次退出應用程序的功能。想要做到計時處理,就需要獲取到當前時間,計算兩次點擊之間的時間差

獲取當前時間:

DateTime.now()

計算當前時間和上次點擊的時間差:

DateTime.now().difference(_lastPressedAt)

時間差判斷(是否大於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;//上次點擊的時間
  @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))){
                //兩次點擊間隔超過1秒,重新計時
                _lastPressedAt = DateTime.now();
                print(_lastPressedAt);
                return false;
              }
              return true;
            }
        ),
      ),
    );
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM