Flutter WillPopScope 双击返回与界面退出提示

在码农的世界里,优美的应用体验,来源于程序员对细节的处理以及自我要求的境界,年轻人也是忙忙碌碌的码农中一员,每天、每周,都会留下一些脚印,就是这些创作的内容,有一种执着,就是不知为什么,如果你迷茫,不妨来瞅瞅码农的轨迹。

如果你有兴趣 你可以关注一下公众号 biglead 来获取最新的学习资料。

在Android中点击物理返回按钮,或者是全面屏的手势退出,或者是iOS中的左滑退出,在Flutter中可使用WillPopScope 拦截退出事件

本文章的效果

在这里插入图片描述

核心代码就是

 @override
  Widget build(BuildContext context) {
    //返回 或者说退出页面里的提示
    return WillPopScope(
      onWillPop: () async {
        //拦截 返回true 表示不拦截
        return false;
      },
      child: Scaffold(..);
  }
实现双击返回提示退出
main() {
  runApp(MaterialApp(
    //不显示 debug标签
    debugShowCheckedModeBanner: false,
    //显示的首页面
    home: DemoWillPopScope(),
  ));
}

///代码清单
class DemoWillPopScope extends StatefulWidget {
  @override
  _DemoWillPopScopeState createState() => _DemoWillPopScopeState();
}

class _DemoWillPopScopeState extends State<DemoWillPopScope> {


  //上一次点击事件
  int pretime = 0;

  @override
  Widget build(BuildContext context) {
    //返回 或者说退出页面里的提示
    return WillPopScope(
      onWillPop: () async {
        print("返回");
        //当前时间
        int now = DateTime.now().millisecond;
        //计算时间差
        int flag = now - pretime;
        //两次点击时间太长不做处理
        if (flag > 1000) {
          print("返回1");
          pretime = now;
          return false;
        }
        print("返回2");
        showTips();
        //拦截
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text("拦截返回按钮"),
        ),
        body: Container(
          padding: EdgeInsets.all(30),
          child: Column(
            children: [],
          ),
        ),
      ),
    );
  }

  void showTips() async {
    bool flag = await showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: Text("提示"),
            content: Text("您确定要退出吗???"),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                  child: Text("确定")),
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                  child: Text("取消"))
            ],
          );
        });
    if (flag) {
      //退出当前页面
    }
  }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早起的年轻人

创作源于分享

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值