在颤动中按下后退按钮时将您的应用程序发送到后台

Pun*_*20g 3 dart flutter

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

Sup*_*ode 8

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

https://pub.dev/packages/move_to_background


小智 5

03.2020 更新

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

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(
    ...
  ),
);
}
Run Code Online (Sandbox Code Playgroud)

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)
            }
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)


小智 0

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

\n\n

平台代码:

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

您的飞镖代码:

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

来源:\nSergi Castellsagu\xc3\xa9 Mill\xc3\xa1n

\n