【问题标题】:flutter: inter-bloc communication, passing data events between different blocsflutter:块间通信,不同块之间传递数据事件
【发布时间】:2021-01-08 16:32:22
【问题描述】:

我没有找到太多关于集团间通信的信息,所以我想出了一个自己的简单解决方案,可能对其他人有帮助。

我的问题是:对于一个屏幕,我将 2 个块用于不同的信息集群,其中一个也在另一个屏幕上重复使用。虽然传递数据有据可查,但我在弄清楚如何将事件或触发状态传递给/其他集团时遇到了问题。

可能有更好的解决方案,但对于像我这样的其他 Flutter 或 bloc 初学者来说,它可能会有所帮助。相当简单,逻辑也很容易理解。

【问题讨论】:

    标签: flutter events state communication bloc


    【解决方案1】:

    如果您将 Bloc A 作为 Bloc B 的依赖项注入(对我来说看起来很简单,我不需要更多 Bloc),我可以从 Bloc B 获取/设置 Bloc A 中的值(反之亦然)。如果我想将数据返回到 Bloc A,或者如果我只想重新加载 Bloc A 构建,我可以触发 B 的 BlocBuilder 中的事件来传递信息。

    // ========= BLOC FILE ===========
    
    class BlocA extends BlocAEvent, BlocAState> {
      int myAVar = 1;
    }
    
    class BlocB extends BlocBEvent, BlocBState> {
      BlocB({@required this.blocA}) : super(BInitial());
      final BlockA blockA;
      // passing data back and forth is straight forward
      final myBVar = blockA.myAVar + 1;
      blockA.myAVar = myBVar;
    
      @override
      Stream<BState> mapEventToState(BEvent event) async* {
        if (event is BInitRequested) {
          // trigger state change of Bloc B and request also reload of Bloc A with passed argument
          yield LgSubjectShowSingle(blocAReloadTrigger: true);
        }
      }
    }
    
    // ========= UI FILE ===========
    
    class MyPage extends StatelessWidget {
      MyPage({Key key, this.title}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        // inject dependency of page on both Blocs: A & B
        return MultiBlocProvider(
            providers: [
              BlocProvider<BlocA>(
                create: (BuildContext context) =>
                BlocA().add(BlocAInit()),
              ),
              BlocProvider<BlocB>(
                create: (BuildContext context) =>
                BlocB(BlocA: BlocProvider.of<BlocA>(
                        context),).add(BInitRequested()),
              ),
            ],
            child: BlocBuilder<BlocB, BState>(
              builder: (context, state) {
                if (state is BShowData) {
                  // If a reload of Bloc A is requested (we are building for Bloc B, here) this will trigger an event for state change of Bloc A
                  if (state.triggerStmntReload) {
                    BlocProvider.of<BlocA>(context).add(AReloadRequested());
                  };
                  return Text("abc");
                }
              }
            )
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多