Home > database >  BlocBuilder vs BlocListener
BlocBuilder vs BlocListener

Time:07-04

I have a very specific question when reading the documentation.

After reading the BlocBuilder documentation, I then went on by reading about the BlocListener. Everything was pretty clear, until I read this:

The listener is guaranteed to only be called once for each state change unlike the builder in BlocBuilder.

As I understand, in BlocBuilder the builder: gets called every time the bloc state changes (of course in the case in which buildWhen: is omitted and it always returns true as a default value). And in BlocListener the listener: gets called in response to state changes in the bloc.

I can't seem to understand the concept behind the quoted text. Doesn't the builder: in BlocBuilder also get called once for every change in the state of the bloc? Where's that "second" call I'm missing happening?

CodePudding user response:

Every time when a new state is emitted by the bloc it is compared with the previous one, and if they are DIFFERENT, the listener function is triggered.

If in you situation, you are using Equatable with only LoadedState as props, which means when two states are compared only the LoadedState are tested. In this way BLoC consumer thinks that the two states are equal and do not triggers the listener function again.

if you want to update same state just add one state before calling your updating state like this, if you want to update 'LoadedState' state again call 'LoadingState' state before that and than call 'LoadedState' state so BlocListener and BlocBuilder will listen to it

CodePudding user response:

The builder is run as you say upon state change. But the builder function is also run when the framework deems necessary to rebuild.

The listener function is not affected by the frameworks need to rebuild.

  • Related