Flutter:导航返回拦截WillPopScope组件(功能性组件)

导航返回拦截WillPopScope:
 为了避免用户误触返回按钮而导致APP退出,在很多App中都拦截了用户点击返回键的按钮,
 当用户在某一个时间段内点击2次时,才会认为用户是要退出(而非触摸)。Flutter中可以通过WillPopScope来实现返回按钮的拦截。

Flutter:导航返回拦截WillPopScope组件(功能性组件)_第1张图片

Flutter:导航返回拦截WillPopScope组件(功能性组件)_第2张图片

onWillPop是一个回调函数,当用户点击返回按钮的时候调用(包括导航返回按钮以及android物理返回按钮),
* 该回调选哟返回一个Future对象,如果返回的Future最终值为false,则当前路由不出栈。为true时,当前路由出栈退出。
* 通过这个回调来决定是否退出。
import 'package:flutter/material.dart';

void main()=> runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('WillPopScope'),),
        body: WillPopScopeTestRoute(),
      ),
    );
  }
}

class WillPopScopeTestRoute extends StatefulWidget {
  @override
  _WillPopScopeTestRouteState createState() => _WillPopScopeTestRouteState();
}

class _WillPopScopeTestRouteState extends State {
  DateTime _lastPressedAt;//上次点击时间
  
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
        if(_lastPressedAt == null || DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1)){
          //2次点击间隔超过1秒则重新记时
          _lastPressedAt = DateTime.now();
          return false;
        }
        return true;
      },
      child: Container(
        alignment: Alignment.center,
        child: Text('1秒内连续按了2次返回键退出。'),
      ),
    );
  }

}

WillPopScope组件通过这个再配合逻辑就可以实现2秒钟连续点击不是退出页面的效果。

在Android中,要实现这种效果,需要重写onBackPressed()方法,再利用time stamp(时间戳)来处理相应的逻辑。

 

 

 

 

你可能感兴趣的:(Flutter)