Flutter学习笔记 按返回键直接回到桌面,不退出APP

  • Post author:
  • Post category:其他


在Flutter应用中,每次按返回键返回桌面时,APP就自动退出了。为了使返回到桌面时,应用可以在后台继续执行,需要与Android原生进行通讯

首先在android包下的MainActivity中,修改

package com.example.flutter_app;

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
    //通讯名称,回到手机桌面
    private final String CHANNEL = "android/back/desktop";
    //返回手机桌面事件
    static final String eventBackDesktop = "backDesktop";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);

        initBackToDesktop();
    }

    //注册返回到手机桌面事件
    private void initBackToDesktop() {
        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                        if (methodCall.method.equals(eventBackDesktop)) {
                            moveTaskToBack(false);
                            result.success(true);
                        }
                    }
                }
        );
    }
}

接下来在Flutter的lib下添加一个android_back_desktop.dart文件:

import 'package:flutter/services.dart';

class AndroidBackDesktop{
  //通讯名称,回到手机桌面
  static const String CHANNEL = "android/back/desktop";
  //设置回退到手机桌面事件
  static const String eventBackDesktop = "backDesktop";

  //设置回退到手机桌面方法
  static Future<bool> backToDesktop() async {
    final platform = MethodChannel(CHANNEL);
    //通知安卓返回到手机桌面
    try{
      await platform.invokeMethod(eventBackDesktop);
    }
    on PlatformException catch (e){
      print("通信失败,设置回退到安卓手机桌面失败");
      print(e.toString());
    }
    return Future.value(false);
  }
}

最后在main.dart中使用WillPopScope包裹,在onWillpop中调用通知回到桌面方法:

import 'package:flutter/material.dart';
import 'package:flutter_app/android_back_desktop.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.display1,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        ),
        onWillPop: AndroidBackDesktop.backToDesktop);
  }
}

效果:

在这里插入图片描述



版权声明:本文为weixin_42215775原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。