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.

I have Bloc B, created and provided in screen 1.

Bloc B has a reference to Bloc A and can add events to Bloc A inside mapEventToState of Bloc B.

Now the weird thing:

Inside screen 1, I have a BlocBuilder of Bloc A,

If I add events directly ( blocAReference.add(blockAEvent) the BlocBuilder gets called when the state changes),

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 printing to console that the event was added to Bloc A)

I am using the flutter_bloc library.


I figured out what was wrong.

The logic is all good except for one thing, I am using injectable library to manage dependencies,

and I was annotating my Bloc A as @Injectable(),

so when the library wants to inject Bloc A into Bloc B‘s constructor,

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>()

So there are 2 solutions:

  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 (i.e. as a function parameter)
  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

Answered By – Haidar

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.