当用户返回应用程序(从后台)时,如何刷新页面?

jac*_*per 2 flutter

现在,我的应用程序可以刷新的唯一方法(它是一个新闻应用程序,因此需要不断刷新)有两种方法:1)通过向上滚动刷新或2)从后台杀死应用程序后重新启动应用程序。

我想要做到这一点,以便当用户刚刚返回应用程序时(假设我正在使用我的应用程序,然后我去微信发送文本,然后我回来),应用程序就会刷新。

这是刷新滚动代码。

final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
new GlobalKey<RefreshIndicatorState>();
Run Code Online (Sandbox Code Playgroud)

然后它调用这个函数:

Future<void> _refresh() async {
  print("Refreshed");
  Navigator.pushReplacement(
    context,
    MaterialPageRoute(
      builder: (context) => MyHomePage(),
    ),
  ).then((value) => null);
}
Run Code Online (Sandbox Code Playgroud)

我应该做什么来实现我所需要的?

有没有办法检查某人是否“返回”我的应用程序?然后我就可以调用该函数了。

小智 6

您需要订阅应用程序生命周期。在 Flutter 中,它的构建方式与原生不同。然而,我去年偶然发现了一篇很好的文章,试图完成同样的事情:

https://medium.com/pharos-product/flutter-app-lifecycle-4b0ab4a4211a

实现的要点如下:

class MyHomePage extends StatefulWidget {
  @override _MyHomePageState createState() => _MyHomePageState();
}

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

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print('state = $state');
  }

  @override
  Widget build(BuildContext context) {
    return YourWidget();
  }
}
Run Code Online (Sandbox Code Playgroud)