zoukankan      html  css  js  c++  java
  • Flutter点击两次返回键退出APP

    在APP中一些页面为了防止用户操作失误点击到返回键导致退出APP,可以设置其一定时间内点击两次返回键才允许退出APP,完成这个功能可以通过WillPopScopeSystemNavigator.pop实现

    我们先来看一下效果:

     

    要实现这个效果我们需要先在外层包裹WillPopScope用来监听用户点击返回键

    Widget build(BuildContext context) {
        return WillPopScope(
          child: Scaffold(
            body: Center(
              child: Text('点击两次返回退出APP'),
            ),
          ),
          onWillPop: (){
            // 点击返回键的操作
          },
        );
      }
    

      

    包裹好WillPopScope之后你会发现你再点击返回键就没效果了

    然后我们需要先做好一个时间的判断,比如两次点击在两秒之内(可以通过difference对比两个时间的时间差)即可进行退出操作

    DateTime lastPopTime;
    
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
          child: Scaffold(
            body: Center(
              child: Text('点击两次返回退出APP'),
            ),
          ),
          onWillPop: (){
            // 点击返回键的操作
            if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: 2)){
              lastPopTime = DateTime.now();
              Toast.toast(context,msg: '再按一次退出');
            }else{
              lastPopTime = DateTime.now();
              // 退出app
            }
          },
        );
      }
    

      

    最后我们再通过执行SystemNavigator.pop完成退出,需引用

    import 'package:flutter/services.dart';
    

      

    最终代码

    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');
            }
          },
        );
      }
    

      

    到这就可以实现啦~

    Toast.toast();这个提示框是自己封装的一个小组件,需要用到的可以看https://www.cnblogs.com/gxsyj/p/11018117.html

  • 相关阅读:
    Setting up jQuery Unobtrusive Validation
    Valid vs Validate
    HTML Tags containing Vue.js v-if and v-for directives flash at loading
    What does a CSS selector in square brackets select in HTML?
    Template refs
    How to check if a variable is not null?
    Android中的Context
    Android从零基础到App上线
    ConstraintLayout 使用汇总
    ConstraintLayout的使用
  • 原文地址:https://www.cnblogs.com/gxsyj/p/11104029.html
Copyright © 2011-2022 走看看