Flutter学习笔记(26)--返回拦截WillPopScope,实现1秒内点击两次返回按钮退出程序
程序员文章站
2022-07-02 13:04:40
在实际开发中,为了防止用户误触返回按钮导致程序退出,通常会设置为在1秒内连续点击两次才会退出应用程序。Android中一般的处理方式是在onKeyDown方法内做计时处理,当keyCode == KeyEvent.KEYCODE_BACK 且 两次点击返回按钮间隔时间小于1秒则退出应用程序,在Flu... ......
如需转载,请注明出处: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; } ), ), ); } }
上一篇: Activiti的25张表