简体   繁体   English

BlocBuilder 的 build 方法在从另一个 bloc 内部添加事件到这个 bloc 时不会被调用

[英]BlocBuilder's build method is not invoked when adding an event to this bloc from inside another bloc

I have bloc A , created and provided above all the widgets of my app.我有bloc A ,在我的应用程序的所有小部件之上创建和提供。

I have Bloc B , created and provided in screen 1 .我有Bloc B ,在screen 1中创建和提供。

Bloc B has a reference to Bloc A and can add events to Bloc A inside mapEventToState of Bloc B . Bloc B具有对Bloc A的引用,并且可以在Bloc BmapEventToState Bloc A添加事件。

Now the weird thing:现在奇怪的事情:

Inside screen 1, I have a BlocBuilder of Bloc A ,在屏幕 1 内,我有一个BlocBuilderBloc A

If I add events directly ( blocAReference.add(blockAEvent) the BlocBuilder gets called when the state changes),如果我直接添加事件( blocAReference.add(blockAEvent) BlocBuilder在 state 更改时被调用),

However when I add an event indirectly to Bloc A ( blocBrefrence.add(blockBEvent) and then inside mapEventToState of Bloc B I add event to Bloc A ), then the BlocBuilder is not invoked (but I can assure by print ing to console that the event was added to Bloc A )但是,当我将事件间接添加到Bloc AblocBrefrence.add(blockBEvent) ,然后在Bloc BmapEventToState中添加事件到Bloc A )时,不会调用BlocBuilder (但我可以通过print向控制台保证事件已添加到Bloc A

I am using the flutter_bloc library.我正在使用flutter_bloc库。

I figured out what was wrong.我发现出了什么问题。

The logic is all good except for one thing, I am using injectable library to manage dependencies,逻辑都很好,除了一件事,我正在使用injectable库来管理依赖项,

and I was annotating my Bloc A as @Injectable() ,我将我的Bloc A注释为@Injectable()

so when the library wants to inject Bloc A into Bloc B 's constructor,因此,当库想要将Bloc A注入Bloc B的构造函数时,

it was creating a new instance of Bloc A every time and that instance was different from the one I was listening to in the BlocBuilder (the one I am listening to is the one provided on top of the widget tree, I am looking it up using context.bloc<BlocA>() )它每次都在创建一个Bloc A的新实例,并且该实例与我在BlocBuilder中收听的实例不同(我正在收听的是在小部件树顶部提供的实例,我正在使用context.bloc<BlocA>() )

So there are 2 solutions:所以有2个解决方案:

  1. I keep the @Injectable() annotation on Bloc A but now I don't inject Bloc A into Bloc B but rather I send the instance of Bloc A with every event added to Bloc B (ie as a function parameter)我在Bloc A上保留@Injectable()注释,但现在我不将Bloc A注入Bloc B而是发送Bloc A的实例,并将每个事件添加到Bloc B (即作为 function 参数)
  2. I remove @Injectable() annotation from Bloc A and replace it with @LazySingleton so that all lookups using context.bloc<BlocA>() will make injectable library give me the same instance of the Bloc A which I created above all my widgets我从Bloc A中删除@Injectable()注释并将其替换为@LazySingleton以便所有使用context.bloc<BlocA>()的查找将使injectable库为我提供与我在所有小部件之上创建的Bloc A相同的实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM