美文网首页
Flutter拦截返回事件

Flutter拦截返回事件

作者: itfitness | 来源:发表于2022-11-19 15:24 被阅读0次

    目录

    前言

    一般应用都会在主页面拦截返回事件,以防止用户误点返回,所以会在一定的时间内需要用户返回两次才可以退出应用

    效果实现

    这里我们使用WillPopScope来进行拦截返回事件,具体如下:

    class MainPage extends StatefulWidget {
      const MainPage({Key? key}) : super(key: key);
    
      @override
      State<MainPage> createState() => _MainPageState();
    }
    
    class _MainPageState extends State<MainPage> {
      DateTime? lastPressedAt; //上次点击时间
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: () async {
            if (lastPressedAt == null ||
                DateTime.now().difference(lastPressedAt!) > Duration(seconds: 3)) {
              //两次点击间隔超过1秒则重新计时
              lastPressedAt = DateTime.now();
              ToastUtil.showToast("再按一次退出应用");
              return false;
            }
            return true;
          },
          child:  Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0.2,
              centerTitle: true,
              title: Text(titles[currentIndex],style: TextStyle(
                  color: Colors.black
              ),),
            ),
            body: Text("测试"),
          ),
        );
      }
    }
    

    其中显示Toast的是使用的第三方的依赖fluttertoast,具体使用可以去pub.dev中查找,这里我把Toast封装了一下

    import 'package:fluttertoast/fluttertoast.dart';
    import 'package:flutter/material.dart';
    
    class ToastUtil{
      static showToast(String msg){
        Fluttertoast.showToast(
            msg: msg,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.black87,
            textColor: Colors.white,
            fontSize: 16.0
        );
      }
    }
    

    以上代码运行后的效果如下:


    相关文章

      网友评论

          本文标题:Flutter拦截返回事件

          本文链接:https://www.haomeiwen.com/subject/qosdxdtx.html