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 @ 2019-09-05 15:50  CurtisWgh  阅读(3048)  评论(5编辑  收藏  举报