Bloc and Cubit
Learn about the differences between Bloc and Cubit and when to use each of them.
We'll cover the following
The flutter_bloc
library includes two state management tools: Blocs and Cubits. While they have many similarities, they also have some significant differences. Blocs manage complex state changes, whereas Cubits manage simpler state changes. Cubits contain less boilerplate code than Blocs, making them more suitable for simple use cases.
Blocs
Blocs are the foundation of the BLoC library. A Bloc is in charge of managing a state and exposing it to the widget tree. It receives a stream of events, processes them, and then updates the stream of states.
For the Bloc syntax, we define a class that extends the Bloc
class and accepts two type parameters: event
type and state
type. We then use the super()
method to initialize the Bloc’s initial state in the constructor.
In the constructor of a Bloc
, we use the on
keyword to listen for specific events and map them to a new state using the mapEventToState()
function. Custom functions cannot be used in Bloc
classes because we can’t call them. In the widget tree, we can only add events to the BLoC stream.
Here is an example of a simple Bloc that manages a counter:
Get hands-on with 1200+ tech skills courses.