Flutter拦截返回事件

2022-11-19  本文已影响0人  itfitness

目录

前言

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

效果实现

这里我们使用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
    );
  }
}

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


上一篇下一篇

猜你喜欢

热点阅读