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

How streams behave when flutter app transitions between AppLifecycleStates?

当 flutter 应用程序过渡到 inactivedetachedpaused 时,它可能有活跃的流订阅。当应用程序在这些状态之间移动时,这些订阅会发生什么情况?转换到特定状态时,我应该注意 cancelling/restarting 订阅吗?

这取决于您是否要在应用处于 inactivepaused 时暂停 Stream

更改 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();
  }
}