Flutter 返回键监听,提示再按一次退出app

Flutter 返回键监听,提示再按一次退出app


直接贴代码

 @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,

        // theme: ThemeData(primarySwatch: Colors.red, primaryColor: Colors.blue),
        home: WillPopScope(
          child: Scaffold(
            body: Tabs(),
          ),
          onWillPop: () async {
            // 点击返回键的操作
            if (lastPopTime == null ||
                DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
              lastPopTime = DateTime.now();
              Fluttertoast.showToast(
                msg: '再按一次退出',
                fontSize: 14,
                gravity: ToastGravity.BOTTOM,
                timeInSecForIos: 1,
                textColor: Colors.black,
              );
            } else {
              lastPopTime = DateTime.now();
              // 退出app
              await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            }
          },
        ),
        // initialRoute: '/',
        onGenerateRoute: onGenerateRoute,
      ),
    );
  }

使用 WillPopScope包裹住Scaffold,onWillPop是监控返回键方法,这边用到的Fluttertoast吐司弹框是引得第三方,如果有需要查看前面文章。

Flutter中,你可以使用`WillPopScope`来监听页面的返回操作。`WillPopScope`是一个Widget,它可以监听用户按下返回按钮或者类似的导航手势,然后执行相应的操作。 下面是一个示例代码,展示如何使用`WillPopScope`来监听页面返回: ```dart class YourPage extends StatelessWidget { @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { // 在这里执行你希望执行的操作 // 返回true表示允许返回返回false表示阻止返回 // 例如,你可以弹出一个对话框询问用户是否确认返回 bool confirmExit = await showDialog( context: context, builder: (BuildContext context) => AlertDialog( title: Text('确认退出?'), content: Text('确定要离开此页面吗?'), actions: [ FlatButton( child: Text('取消'), onPressed: () { Navigator.of(context).pop(false); // 阻止返回 }, ), FlatButton( child: Text('确定'), onPressed: () { Navigator.of(context).pop(true); // 允许返回 }, ), ], ), ); return confirmExit ?? false; // 如果对话框关闭时没有选择,则默认不允许返回 }, child: Scaffold( appBar: AppBar( title: Text('Your Page'), ), body: Center( child: Text('Your Page Content'), ), ), ); } } ``` 在上述示例中,我们将整个页面包裹在`WillPopScope`中,并指定了`onWillPop`回调函数。在回调函数中,你可以执行任何你希望在页面返回时进行的操作。在这个示例中,我们弹出一个对话框来询问用户是否确认返回。用户的选择将决定是否允许返回。 注意:`WillPopScope`只能监听物理返回按钮或者类似的导航手势,不能监听页面中的其他返回操作,例如点击一个返回按钮。如果你想监听页面中其他返回操作,你需要手动实现相应的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值