Alex Stroescu
Alex Stroescu

Reputation: 1158

Accesing a BLoC using getit instead of context not working

I am trying to access a BLoC instance without actually using the context, but getIt instead. The versions I have are:

  flutter_bloc: ^8.1.1
  injectable: ^2.1.0
  get_it: ^7.2.0
  injectable_generator: ^2.1.3

I have the BLoC registered in getit using "@injectable". The problem goes like this:

Firstly, I provide the bloc using:

BlocProvider(
      lazy: false,
      create: (context) => getIt<BlocA>(),
    ),

I am trying to use:

getIt<BlocA>().add(
               BlocAEvent.started(),
             );

Lets say that on started event I log something in the console and emit a new state, when I use getIt to add the started event, it will actually do something and log the started event in the console. But, if I am using a BlocBuilder with BlocA in the UI, that Builder will not actually get the new emitted state. So, the log happens, but the emit after the log is not caught by BlocBuilder, which will remain to its initial state. It is clear to me that getIt does something to another instance of BlocA, cause if I use context to emit BlocA Started event everything works normally and BlocBuilder gets the new emitted state after the log.

Why is it not working? I am providing getIt() not just BlocA. (the stream of states from getIt() and the stream from context.read() have different hashCodes also)

Upvotes: 1

Views: 648

Answers (1)

If you want to listen to an event, include everything in a BlocListener. In this way, you will have a listener for each of the states that you emit, thus guaranteeing and validating when it is a state that you want.

For example:

return BlocListener<DistributionCenterBloc, DistributionCenterState>(
        listenWhen: (previous, current) =>
            previous.success != current.success ||
            previous.errorResponse != current.errorResponse,
        listener: (context, state) {
          if (state.success != '') {
            audioCache!.play(audioCorrect);
          }

In this way, I validate what the states are and make the pertinent decision for each one of them.

Upvotes: 0

Related Questions