I am practicing with flick_bloc and I wonder when to use BlocBuilder, when to use BlocListener and when to use BlocConsumer. I asked a few people, they said that BlocBuilder is used the most and I also started and just practiced with it, but it seems that Blocbuilder only changed for the first time, I don’t know if it’s true. Can you guys give me some comments on these spellings
3
Answers
BlocBuilder:
You can use it to just build out your widgets, but the draw back is that you can’t build in Snackbars or Dialogs into the flow, because you must return a widget in blocbuilder and you don’t want to return a snackbar or dialog.BlocListener:
This would permit you to use your dialogs and snackbars, but the issue is that it can’t let you do anything a blocbuilder would let you do. Which is as you might have guessed, is to return a widget, it’s more suited for dismissible UI components like the dialogs and snackbars.BlocConsumer:
This widget helps you combine both a BlocListener and a BlocBuilder, so you can return static components and dismissible UI components.So if you won’t need Snackbars or Dialogs, use a
BlocBuilder
, If you need Snackbars or Dialogs, use aBlocListener
. If you want both of them to work in synergy use aBlocConsumer
.Bloc Builder
Bloc Listener
Bloc Consumer
Code Without Bloc Consumer:
Code using Bloc Consumer:
BlocBuilder
This is used when we want to draw a Widget based on what is the current State. In the following example a new “text” gets drawn every time the state changes.
Sample Example
BlocListener
This is just a listener not a builder (like the above), that means that its job is keep listening for new changes in the state and not to return a widget. You can use listener when you want to show any dialog or any toast, or navigation from one page to another(these are few examples).
Sample Example
BlocConsumer
This is used when we want to draw something based on the current state and execute some actions depending on the new arriving states. This is a mix between “BlocListener” and “BlocBuilder”.
Sample Example