如何在didChangeAppLifecycleState(iOS和android设备)上完全重启Flutter应用程序

3
我有一个应用程序,当 AppLifeCycleState.paused 时,我希望完全重新启动它。这个功能在 android (Pixel 3 XL Api 28) 上似乎可以正常工作,但在 iOS 设备上不行。

iOS 原生等效方法:

在我的本机 iOS 版本的应用程序中,在 AppDelegate 的 applicationDidEnterBackground 函数中运行 exit(0)。

我尝试使用 WidgetBindingObserver 使 MyApp 成为有状态的,并监听状态的变化。在 .paused 状态下,我尝试执行 exit(0)SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop');

位于 MyApp 状态内部

 @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.paused:
        print('paused state');
        SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop');
        //I have also tried exit(0); here.
        break;
      case AppLifecycleState.resumed:
        print('resumed state');
        break;
      case AppLifecycleState.inactive:
        print('inactive state');
        break;
      case AppLifecycleState.suspending:
        print('suspending state');
        break;
    }
  }

最初的回答:我期望该应用程序会退出,再次打开后会重新启动,但实际上它根本不会退出。它只是在暂停状态下继续运行之前的位置。这种行为仅在iOS设备上发生。
我明白我的代码不是一个完全工作的最小示例-如果您需要我设置一个供人们尝试的示例,请告诉我。

你可以使用'restart_app'插件。它可以在操作系统级别重新启动整个应用程序,并且还支持iOS平台。 - undefined
1个回答

0

好的,所以我解决了这个问题,但是我不确定为什么之前尝试使用 exit(0) 没有起作用。

我已经将 didChangeAppLifecycleState 函数修改如下。

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.paused:
        print('paused state');
        SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop');
        if (Platform.isIOS) {
          exit(0);
        }
        break;
      case AppLifecycleState.resumed:
        print('resumed state');
        break;
      case AppLifecycleState.inactive:
        print('inactive state');
        break;
      case AppLifecycleState.suspending:
        print('suspending state');
        break;
    }
  }

通过添加以下代码,该应用现在可以在安卓和iOS上退出了。
if (Platform.isIOS) {
          exit(0);
        }

如果有人能够解释一下为什么仅仅使用exit(0)本身不起作用,我会很想更好地理解这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接