Flutter中,解决按下返回键将应用挂起到后台,并不会退出的问题
参考地址:传送门
问题:
由于应用中牵扯到了聊天的功能,由于Flutter默认的返回是直接退出APP的,所以需要我们自己特殊配置一下
注意:Flutter在最新的版本中,java代码已经逐渐由kotlin代码替代,所以下面将会展示两个版本的代码来解决这个问题
旧版本Flutter:
第一步:
首先查找到以下路径
打开这个MainActivity.java
保留第一行包名代码!!!
,将下面这些代码复制进去替换掉
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.view.KeyEvent;
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);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("backDesktop")) {
result.success(true);
moveTaskToBack(false);
}
}
}
);
}
}
第二步:
创建个Dart文件,文件名自己取,我这里取名为android_back.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);
}
}
第三步:
首先引入进来你之前写的这个dart文件,在main里监听最外层返回键,然后通讯原生,执行 moveTaskToBack(false) 回到手机桌面不退出app
import 'package:flutter/material.dart';
import 'package:shoppingmall/android_back.dart';
void main() async {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provide<ConfigModel>(
builder: (context, child, configModel) {
return MaterialApp(
title: 'test',
debugShowCheckedModeBanner: false,
home: WillPopScope(
onWillPop: () async {
AndroidBackTop.backDeskTop(); //设置为返回不退出app
return false; //一定要return false
},
child: Text("Test"),
),
);
},
);
}
}
新版本Flutter:
新版本的flutter只是在安卓里的那个文件有所不同,代码已经变为了kotlin的格式,所以,里面的代码我们要写成kotlin的样子
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
import android.view.KeyEvent
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
//通讯名称,回到手机桌面
private val CHANNEL = "android/back/desktop"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { methodCall, result ->
if (methodCall.method == "backDesktop") {
result.success(true)
moveTaskToBack(false)
}
}
}
}
如何结合路由使用??
class _MyAppState extends State<MyApp> {
int _currentIndex = 0; // 展示下标
List pageList = [HomePage(), MessagePage(), UserPage()];
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
AndroidBackTop.backDeskTop(); //设置为返回不退出app
return false; //一定要return false
},
child: Scaffold(
appBar: AppBar(title: Text('头部')),
body: pageList[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed, //允许多个菜单
onTap: (index) {
setState(() {
this._currentIndex = index;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('首页')),
BottomNavigationBarItem(
icon: Icon(Icons.message), title: Text('消息')),
BottomNavigationBarItem(icon: Icon(Icons.people), title: Text('用户'))
],
),
),
);
}
}
额外知识
java代码如何转换成kotlin??? kotlin如何转换成Java????
最后只需要运行程序,就可以体验