flutter 导航返回拦截(WillPopScope)

该博客介绍了如何使用Flutter的WillPopScope widget来防止用户意外退出应用。通过设置一个时间间隔,只有当用户在短时间内连续两次点击返回按钮,才会真正退出应用。这为用户提供了一个确认退出的机制,增加了用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导航返回拦截(WillPopScope),为了防止用户点击返回退出

DateTime lastPopTime; 
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          title: Text('点击两次返回退出APP',style: TextStyle(color: Colors.white,fontSize: 20),),
        ),
        body: Center(
          child: Text('点击两次返回退出APP'),
        ),
      ),
      onWillPop: () async{
        // 点击返回键的操作
        if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: 2)){
          lastPopTime = DateTime.now();
          Toast.toast(context,msg: '再按一次退出');
        }else{
          lastPopTime = DateTime.now();
          // 退出app
          await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
        }
      },
    );
  }

{Future<bool> Function() onWillPop} 在用户点击返回键时,将会调用这个方法

Called to veto attempts by the user to dismiss the enclosing [ModalRoute].

If the callback returns a Future that resolves to false, the enclosing route will not be popped.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

computerclass

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值