zoukankan      html  css  js  c++  java
  • flutter 返回键监听

    本篇为继上片监听返回键基础下优化:

    以下做返回键监听两种情况:

    import 'package:fluttertoast/fluttertoast.dart';  //提示第三方插件

    1. 单击提示双击退出,双击时退出App

    DateTime _lastPressedAt; //上次点击时间
    main.dart-MyApp中:
    home: WillPopScope( // 监听返回键Widget
      onWillPop: () async { // 点击返回键即触发该事件
        if (_lastPressedAt == null) { //首次点击提示...信息
          Fluttertoast.showToast(
            msg: "双击退出程序...",
            gravity: ToastGravity.BOTTOM,
            timeInSecForIos: 1,
            backgroundColor: Colors.grey[400],
            textColor: Colors.white,
            fontSize: ScreenUtil().setWidth(12),
          );
        }
        if (_lastPressedAt == null || DateTime.now().difference(_lastPressedAt) >  Duration(seconds: 1)) {
          //两次点击间隔超过1秒则重新计时
          _lastPressedAt = DateTime.now();
          return false; // 不退出
        }
        return true;  //退出
      },
      child: Pages(),
    ),

    2. 单击返回手机桌面,不退出App

       main.dart文件

    import 'package:flutter_smart_park/untils/android_back_desktop.dart';
    
    home: WillPopScope(
      onWillPop: () async {
         AndroidBackTop.backDeskTop();
            return false;
          },
       child: configProvide.token == '0' ? UserLogIn() : Pages(),
    ),
    

       android_back_desktop.dart

    import 'package:flutter/services.dart';
    import 'package:flutter/material.dart';
    class AndroidBackTop {
      //初始化通信管道-设置退出到手机桌面
      static const String CHANNEL = "android/back/desktop";
      //设置回退到手机桌面
      static Future<bool> backDeskTop() async {
        final platform = MethodChannel(CHANNEL);
        //通知安卓返回,到手机桌面
        try {
          final bool out = await platform.invokeMethod('backDesktop');
          if (out) debugPrint('返回到桌面');
        } on PlatformException catch (e) {
          debugPrint("通信失败(设置回退到安卓手机桌面:设置失败)");
          print(e.toString());
        }
        return Future.value(false);
      }
    }

    需在MainActivity.java文件中添加配置:

    import android.os.Bundle;
    import android.view.KeyEvent;import io.flutter.app.FlutterActivity; 
    
    import io.flutter.plugins.GeneratedPluginRegistrant; 
    import io.flutter.plugin.common.MethodCall; 
    import io.flutter.plugin.common.MethodChannel; 
    public class MainActivity extends FlutterActivity {
     //通讯名称,回到手机桌面   private final String CHANNEL = "android/back/desktop";   @Override   protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     GeneratedPluginRegistrant.registerWith(this);
        MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
          MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
              if (methodCall.method.equals("backDesktop")) {
                result.success(true);
                moveTaskToBack(false);  //是否关闭
              } 
            }
          }
        );
      }
    }
    

    附加:  MethodChannel  本地访问

    在客户端,MethodChannel(API)允许发送与方法调用相对应的消息。 在平台方 面,Android(API)上的MethodChannel和 iOS(API)上的 FlutterMethodChannel启用接收方法调用并发回结果

     添加相关依赖
    import io.flutter.plugin.common.MethodCall;
    import io.flutter.plugin.common.MethodChannel;
    import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
    import io.flutter.plugin.common.MethodChannel.Result;
    

     申明变量CHANNEL,值与定义触发事件包名相同,以上android_back_desktop为例:

    private  final String CHANNEL = "android/back/desktop";
    

     在MethodChannel的中调用.setMethodCallHandler() 方法,需要一个MethodCallHandler 对象,是一个匿名内部类,有一个方法onMethodCall,在Flutter发送请求事,onMethodCall方法会执行。

    public class MainActivity extends FlutterActivity {
      private static final String CHANNEL = "android_back_desktop";
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);
        MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
          MethodCallHandler() {
            @Override
            public void onMethodCall(MethodCall methodCall, Result result) {
            }
          }
        );
      }
    }

    onMethodCall方法中有两个参数 MethodCall 和 result,MethodCall 中有关当前请求的信息,例如调用方法的名字changeLife;Result用于发送信息给Flutter。

    在onMethodCall中判断当前请求是否为changeLife,如果是通过result 的 success 返回信息:Life Changed .

    public void onMethodCall(MethodCall methodCall, Result result) {
      if (methodCall.method.equals("backDesktop")){
        String message ="Life Changed";
        result.success(message);
      }
      ...
  • 相关阅读:
    英语Lignaloes沉香木LIGNALOES单词
    英语chrismatite黄蜡石chrismatite单词
    英语cartialgenous鹿茸cartialgenous单词
    英语NanyangJade南阳玉NanyangJade独山玉
    单词chalchiguite硬玉chalchiguite英语
    英语_金丝楠是紫楠(phoebeSheareri)的别名
    英语AquilariaCrassna奇楠沉香
    英语LIGNALOO沉香lignaloo单词
    iOS批量添加SDK自动打包GUI工具
    如何做一个跨平台的游戏App?
  • 原文地址:https://www.cnblogs.com/john-hwd/p/10791157.html
Copyright © 2011-2022 走看看