颤动:整体间通信,在不同集团之间传递数据事件

问题描述

我对整个人际交流的了解并不多,所以我想出了一个自己的简单解决方案,可能会对其他人有所帮助。

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

也许有更好的解决方案,但是对于像我这样的其他扑扑或集团初学者来说,这可能会有所帮助。这很简单,逻辑也很容易遵循。

解决方法

如果将Bloc A作为对Bloc的依赖项注入(对我来说看起来很简单,我不需要其他Blocs),则可以从Bloc中获取/设置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");
            }
          }
        )
    );
  }
}