flutter 监听返回键
### 监听手机返回键(双击退出) ``` import 'package:fluttertoast/fluttertoast.dart'; //提示插件 class WillPopScopeTestRoute extends StatefulWidget { @override WillPopScopeTestRouteState createState() { return new WillPopScopeTestRouteState(); } } class WillPopScopeTestRouteState extends State<WillPopScopeTestRoute> { DateTime _lastPressedAt; //上次点击时间 var status = false; @override Widget build(BuildContext context) { return GestureDetector( onDoubleTap: (){return status=true;}, child: WillPopScope( 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(), ), ); } } main-MyApp中使用 home: WillPopScopeTestRoute(), ``` ### 监听手机返回键(单击返回桌面不退出app) ``` // MainActivity import android.os.Bundle; import android.view.KeyEvent; import io.flutter.app.FlutterActivity; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.GeneratedPluginRegistrant; //通讯名称,回到手机桌面 private final String CHANNEL = "android/back/desktop"; // onCreate方法下 new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) { //通过methodCall可以获取参数和方法名 执行对应的平台业务逻辑即可 if (methodCall.method.equals("backDeskTop")) {//设置 当前flutter页返回到手机桌面 result.success(true);
moveTaskToBack(false); // 调用返回事件 } } } ); // android_back_top文件 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); } } // main文件下使用 home: WillPopScope( onWillPop: () async { AndroidBackTop.backDeskTop(); return false; }, child: Pages(), ), ```