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;
            }
        ),
      ),
    );
  }
}
复制代码

 

posted @   CurtisWgh  阅读(3159)  评论(5编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示