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

时间:2019-04-05 15:56:21

标签: dart flutter

扑打代码,可在按下“后退”按钮时将应用程序发送到后台。我想像单击主页按钮一样对应用程序单击后退按钮,以使应用程序在后台最小化,现在,当我单击后退按钮时,它将杀死该应用程序。我正在使用willPopScope使其正常运行,但没有帮助

4 个答案:

答案 0 :(得分:5)

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

https://pub.dev/packages/move_to_background

答案 1 :(得分:3)

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)
            }
        }
    }
}
}

答案 2 :(得分:0)

尝试使用

SystemChannels.platform.invokeMethod('SystemNavigator.pop');

在此处引用文档:https://docs.flutter.io/flutter/services/SystemNavigator/pop.html

答案 3 :(得分:0)

从这里: 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)
                }
            }
        }
    }
}

您的DART代码:

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(),
          ],
        ),
      ),
    );
  }

信用至: SergiCastellsaguéMillán