BlocBuilder's build method is not invoked when adding an event to this bloc from inside another bloc
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:
- I keep the
@Injectable()
annotation onBloc A
but now I don't injectBloc A
intoBloc B
but rather I send the instance ofBloc A
with every event added toBloc B
(i.e. as a function parameter) - I remove
@Injectable()
annotation fromBloc A
and replace it with@LazySingleton
so that all lookups usingcontext.bloc<BlocA>()
will makeinjectable
library give me the same instance of theBloc A
which I created above all my widgets
Haidar
Self-taught This site is toxic but - unfortunately - necessary
Updated on December 21, 2022Comments
-
Haidar over 1 year
I have
bloc A
, created and provided above all the widgets of my app.I have
Bloc B
, created and provided inscreen 1
.Bloc B
has a reference toBloc A
and can add events toBloc A
insidemapEventToState
ofBloc B
.Now the weird thing:
Inside screen 1, I have a
BlocBuilder
ofBloc A
,If I add events directly (
blocAReference.add(blockAEvent)
theBlocBuilder
gets called when the state changes),However when I add an event indirectly to
Bloc A
(blocBrefrence.add(blockBEvent)
and then insidemapEventToState
ofBloc B
I add event toBloc A
), then theBlocBuilder
is not invoked (but I can assure byprint
ing to console that the event was added toBloc A
)I am using the
flutter_bloc
library.