为了避免用户误触返回按钮而导致APP退出,在很多APP中都拦截了用户点击返回键的按钮,然后进行一些防误触判断,比如当用户在某一个时间段内点击两次时,才会认为用户是要退出(而非误触)。Flutter中可以通过WillPopScope来实现返回按钮拦截,我们看看WillPopScope的默认构造函数:

  1. const WillPopScope({
  2. ...
  3. @required WillPopCallback onWillPop,
  4. @required Widget child
  5. })

onWillPop是一个回调函数,当用户点击返回按钮时被调用(包括导航返回按钮及Android物理返回按钮)。该回调需要返回一个Future对象,如果返回的Future最终值为false时,则当前路由不出栈(不会返回);最终值为true时,当前路由出栈退出。我们需要提供这个回调来决定是否退出。

示例1:

为了防止用户误触返回键退出,我们拦截返回事件。当用户在1秒内点击两次返回按钮时,则退出;如果间隔超过1秒则不退出,并重新记时。代码如下:

lib/routes/route_will_pop.dart
  1. import 'package:flutter/material.dart';
  2. class RouteWillPop extends StatefulWidget {
  3. RouteWillPop({
  4. Key key,
  5. @required this.child,
  6. }) : assert(child != null),
  7. super(key: key);
  8. final Widget child;
  9. @override
  10. _RouteWillPopState createState() => _RouteWillPopState();
  11. }
  12. class _RouteWillPopState extends State<RouteWillPop> {
  13. DateTime _lastPressedAt; //上次点击时间
  14. @override
  15. Widget build(BuildContext context) {
  16. return WillPopScope(
  17. child: widget.child,
  18. onWillPop: () async {
  19. // 当用户在1秒内点击两次返回按钮时,则退出;如果间隔超过1秒则不退出,并重新记时。
  20. if (_lastPressedAt == null ||
  21. DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1)) {
  22. _lastPressedAt = DateTime.now();
  23. return false;
  24. }
  25. return true;
  26. },
  27. );
  28. }
  29. }

页面使用
  1. import "package:flutter/material.dart";
  2. import 'package:app1/routes/route_will_pop.dart';
  3. class TestPage extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. return RouteWillPop(
  7. child: Scaffold(
  8. appBar: AppBar(title: Text('导航拦截返回 demo')),
  9. body: Text('1秒内连续按两次返回键退出'),
  10. ),
  11. );
  12. }
  13. }