• 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;
                }
            ),
          ),
        );
      }
    }

     

  • 相关阅读:
    [转]23种经典设计模式的java实现_5_职责链模式
    ARM汇编伪指令介绍
    avrstudio 5 按键控制led移位
    linux 应用程序里面调用shell
    avrstudio 5 同时点亮8只数码管
    从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
    avrstudio 5 矩阵键盘
    linux 格式化输出输入函数
    Google 浏览器(2011)书签同步
    linux下面的路径问题
  • 原文地址:https://www.cnblogs.com/upwgh/p/11466544.html
Copyright © 2020-2023  润新知