Flutter点击返回键,回到桌面,但不退出APP的实现
前言
只有Android手机上才会有返回APP的操作,所以以下所说的是针对Flutter的Android平台上开发,现在Flutter的版本已经升级到1.22.0以上了,很多旧方法都不能用了,网络上有很多案例都是针对旧的Flutter版本,所以我这边就做过新版本的该功能,方便大家参考一下
一、编写回到桌面方法的插件
这是新旧Flutter编写返回到桌面的最大区别,以前可以在MainActivity直接编写能用的插件,但是现在不行了,很多方法都没有了,因此,我们需要新启一个插件 app_util_plugin,编写网上有很多教程,这里就不在赘述了
package com.app.app_util_plugin;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import io.Flutter.embedding.engine.plugins.FlutterPlugin;
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;
import io.Flutter.plugin.common.PluginRegistry.Registrar;
/** AppUtilPlugin */
public class AppUtilPlugin implements FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private MethodChannel channel;
private Context mContext;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding FlutterPluginBinding) {
mContext = FlutterPluginBinding.getApplicationContext();
channel = new MethodChannel(FlutterPluginBinding.getBinaryMessenger(), "app_util_plugin");
channel.setMethodCallHandler(this);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else if (call.method.equals("checkUpdateApp")) {
} else if (call.method.equals("navigatetoSystemHome")) {//返回系统首页
Intent intent = new Intent();// 创建Intent对象
intent.setAction(Intent.ACTION_MAIN);// 设置Intent动作
intent.addCategory(Intent.CATEGORY_HOME);// 设置Intent种类
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//标记
mContext.startActivity(intent);
} else {
result.notImplemented();
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
}
二、编写通过MethodChannel调用插件中方法
import 'dart:async';
import 'package:Flutter/services.dart';
class AppUtilPlugin {
static const MethodChannel _channel =
const MethodChannel('app_util_plugin');
//返回系统首页
static void navigatetoSystemHome() async {
await _channel.invokeMethod('navigatetoSystemHome');
}
}
三、使用返回桌面的方法
在main.dart监听系统返回键,当时调用系统返回键时,将它拦截下来,再调用插件中的返回桌面的方法,这样就可以不用退出APP,就可以回到桌面了
MaterialApp(
home: WillPopScope(
onWillPop: () async {
AppUtilPlugin.navigatetoSystemHome();//返回到系统首页
return false;
},
child: HomeMainPage(),
),
navigatorKey: Constant.navKey,
navigatorObservers: [MyApp.routeObserver],
onGenerateRoute: onGenerateRoute,
)
总结
整个过程很简单,希望可以帮到Flutter 的初学者们
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。