didChangeAppLifecycleState 没有按预期工作

Ton*_*ony 7 onresume dart flutter

我希望我了解如何didChangeAppLifecycleState正确工作。

我有页面 A 和页面 B 。当我单击页面 B ( Navigator.of(context).pop();) 中的后退设备按钮时,我希望didChangeAppLifecycleState在页面 A中会被调用,但事实并非如此。

页面A

class _ABCState extends State<ABCrList> with WidgetsBindingObserver {
@override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
            ....
  }

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      setState(() {
        print(...);
      });
    }else{
      print(state.toString());
    }
  }

....
Run Code Online (Sandbox Code Playgroud)

这是initState在页面A。用于调用后端服务的函数。

@override
  void initState() {
    super.initState();  
       _bloc.getList(context);  // return list and populate to ListView
    });
  }
Run Code Online (Sandbox Code Playgroud)

Cop*_*oad 6

您认为这是 Android 的工作方式onResume,但在 Flutter 中,事情不会这样发生。

通常,当系统将应用程序置于后台或将应用程序返回到前台时,会调用此方法。


它主要有4种状态:

resumed:应用程序可见并响应用户输入。

inactive:应用程序处于非活动状态,未接收用户输入。

paused:应用程序当前对用户不可见,不响应用户输入,并在后台运行。

detached:该应用程序仍托管在 Flutter 引擎上,但与任何主机视图分离。


编辑:

当您导航到PageBfrom 时PageA,请使用以下内容:

Navigator.pushNamed(context, "/pageB").then((flag) {
  if (flag) {
    // you're back from PageB, perform your function here
    setState(() {}); // you may need to call this if you want to update UI
  }
});
Run Code Online (Sandbox Code Playgroud)

从 PageB,你可以使用

Navigator.pop(context, true);
Run Code Online (Sandbox Code Playgroud)