【问题标题】:Sending your application to background when back button is pressed in flutter在颤动中按下后退按钮时将您的应用程序发送到后台
【发布时间】:2019-08-27 14:07:28
【问题描述】:

Flutter 代码可在按下后退按钮时将应用程序发送到后台。当我单击返回按钮时,我想将应用程序最小化到后台,就像主页按钮对应用程序所做的那样,现在当我单击返回按钮时,它会杀死应用程序。我正在使用 willPopScope 让它工作,但没有帮助

【问题讨论】:

  • 我相信你现在不能在 Flutter 中做到这一点。您可以尝试MethodChannel 并在双方本地进行。你想让我为 Android 提供一个解决方案吗?

标签: dart flutter


【解决方案1】:

我在 pub.dev 上找到了这个包,它对我来说效果很好,而且很容易使用

https://pub.dev/packages/move_to_background

【讨论】:

  • 这种方法对我来说效果很好!
【解决方案2】:

03.2020 更新

正如@user1717750 所写 - 飞镖代码保持不变,所以它是:

var _androidAppRetain = MethodChannel("android_app_retain");

@override
Widget build(BuildContext context) {
return WillPopScope(
  onWillPop: () {
    if (Platform.isAndroid) {
      if (Navigator.of(context).canPop()) {
        return Future.value(true);
      } else {
        _androidAppRetain.invokeMethod("sendToBackground");
        return Future.value(false);
      }
    } else {
      return Future.value(true);
    }
  },
  child: Scaffold(
    ...
  ),
);
}

MainActivity() 中的代码应如下所示:

class MainActivity: FlutterActivity() {

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine);

    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "android_app_retain").apply {
        setMethodCallHandler { method, result ->
            if (method.method == "sendToBackground") {
                moveTaskToBack(true)
            }
        }
    }
}
}

【讨论】:

    【解决方案3】:

    从这里: https://medium.com/stuart-engineering/%EF%B8%8F-the-tricky-task-of-keeping-flutter-running-on-android-2d51bbc60882

    平台代码:

    class MainActivity : FlutterActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            GeneratedPluginRegistrant.registerWith(this)
    
            MethodChannel(flutterView, "android_app_retain").apply {
                setMethodCallHandler { method, result ->
                    if (method.method == "sendToBackground") {
                        moveTaskToBack(true)
                    }
                }
            }
        }
    }
    

    您的飞镖代码:

    Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: () {
            if (Platform.isAndroid) {
              if (Navigator.of(context).canPop()) {
                return Future.value(true);
              } else {
                _androidAppRetain.invokeMethod("sendToBackground");
                return Future.value(false);
              }
            } else {
              return Future.value(true);
            }
          },
          child: Scaffold(
            drawer: MainDrawer(),
            body: Stack(
              children: <Widget>[
                GoogleMap(),
              ],
            ),
          ),
        );
      }
    

    贷方: Sergi Castellsagué Millán

    【讨论】: