当 Flutter 应用程序在 AppLifecycleState 之间转换时,流的行为如何?

问题描述

Flutter 应用程序转换为 inactivedetachedpaused 时,它可能具有活动流订阅。当应用程序在这些状态之间移动时,这些订阅会发生什么变化?在转换到特定状态时,我是否应该注意取消/重新启动订阅

解决方法

这取决于您是否想在应用处于 Streaminactive 时暂停 paused

更改 ApplifeCycle 状态不会在更改状态时暂停流订阅,并且只会在您关闭应用时取消订阅(如果您在 dispose() 方法中提及)。

您可以尝试使用此代码来测试行为:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  StreamSubscription sub;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print(state);
    print('Paused: ${sub.isPaused}');

    // Here you can cancel or pause subscriptions if necessary
    if (state == AppLifecycleState.paused) {
      sub.pause();
    }

  }

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    sub = Stream.periodic(const Duration(seconds: 1))
        .listen(print);
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return const SizedBox();
  }
}