【问题标题】:Flutter- Understanding the lifecycle of Provider, Bloc and when to dispose the stream [duplicate]Flutter - 了解 Provider、Bloc 的生命周期以及何时处理流 [重复]
【发布时间】:2019-06-13 14:54:45
【问题描述】:

需要了解什么时候应该Bloc模式和Bloc的生命周期(如何释放持有内存的对象)

我有一个从服务器获取数据的屏幕,数据将仅用于单个屏幕。我正在使用 Bloc 模式来显示数据。

当使用 Bloc 模式时,我有一个使用 StatelessWidget 的屏幕。我正在尝试处理“WillPopScope”上的流。一旦处理完毕,流就不能再使用了。因为访问同一个屏幕会导致崩溃,因为我已经用 Bloc 包装了 MaterialApp。

  1. 创建了一个流
    final _leaderBoardList = StreamController<List<dynamic>>.broadcast();
  1. 处理流
    dispose() {
      print('_leaderBoardList disposed');
      _leaderBoardList.close();
    }
  1. 在提供者中包装 Material App:
    LeaderBoardProvider(
        child: MaterialApp(
        title: 'Table View Fetch',
        theme: ThemeData(
          primarySwatch: Colors.teal,
        ),
        home: HomeScreen(),
      ),
      );
  1. Statelesswidget 'WillPopScope',我已经评论了代码的处置,因为据我所知,当前块已创建一次:
  Widget build(BuildContext context) {

    print(' ListView fetch Build called');
    final bloc = LeaderBoardProvider.of(context);
    bloc.fetchLeaderBoards();
    return WillPopScope(
      onWillPop: () async {
        //bloc.dispose();
        return true;
      },
      child: bodyStack(context, bloc),
    );
  }

第一个问题,假设我创建了一个广播流并删除了“WillPopScope”中的代码处置,那么一切都按预期工作,但我认为,这样,我的 Bloc 为应用程序生命周期保留了一个内存.

第二个问题,如何处理在屏幕内使用数据的情况。在这种情况下是否推荐使用 Bloc 模式?

【问题讨论】:

    标签: flutter bloc inherited-widget flutter-provider


    【解决方案1】:

    您不应在 WillPopScope 内处理 BLoC。

    “提供者”的工作是处理 BLoC 的处置:当提供者小部件从树中移除时,它应该关闭流。

    这是通过您的 Provider 作为 StatefulWidget(具有内部私有 InheritedWidget 以公开 BLoC)并覆盖 dispose 方法来实现的。

    示例见Flutter: How to correctly use an Inherited Widget?(与BLoC无关,也没有dispose,但思路类似)。

    【讨论】:

    • 明白了,您正在推荐这种方法,您已在此处回答stackoverflow.com/a/51690319/2644723。
    • 同样在同一个链接中,您提到“ InheritedWidget 的行为方式与其他 Widget 相同。它们的生命周期非常短:通常不超过一次构建调用。如果您想更长时间地存储数据, InheritedWidget 不是你想要的。你需要一个 State。澄清一下,这里的意思是使用 GlobalKey 作为键?
    • 没有。使用实际的 State 子类
    • _ViewControllerState createState() =&gt; _ViewControllerState(); } class _ViewControllerState extends State&lt;ViewController&gt; { ` // 小部件的持久状态放在这里` ` @override` Widget build(BuildContext context) { // return a widget based on the persistent state ` }` } 你的意思是状态子类?你能举个例子吗?
    猜你喜欢
    • 1970-01-01
    • 2022-12-14
    • 2010-12-24
    • 2019-10-26
    • 2017-11-02
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 2021-01-03
    相关资源
    最近更新 更多