flutter: inter-bloc通信,在不同bloc之间传递数据事件

flutter: inter-bloc communication, passing data events between different blocs

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

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

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

如果您将 Bloc A 作为 Bloc B 的依赖注入(对我来说看起来很简单,我不需要更多的 Bloc),我可以 get/set 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");
            }
          }
        )
    );
  }
}