Use Bloc in Flutter to manage states

Tram Ho

Bloc is a lib for state management for Flutter application. BLoC means Business Logic Component . Take ‘Event’ as input and return output as ‘State’. Bloc is based on RxDart.

We can divide the Flutter application architecture into the following three classes:

  1. View Layer’s signboard.
  2. Bloc
  3. Data Layer

So that means Bloc stands between the two classes View and Data.

1. Data Layer

Responsible for providing data from any source. The data provider provides the data tho, and the repository will be the encapsulation of one or more data providers.

2. Bloc or Business Logic

Responsible for receiving event from performance class and returning a new state. Acts as a bridge between the data layer and the presentation layer.

3. Presentation Layer

It is responsible for rendering itself based on one or more states of the block. It also handles user input events and application lifecycle events.

Some concepts for Bloc

1. Events

Event is passed to a Bloc. It’s like the concept action in Redux. In the presentation layer, events are generated by user interaction such as button clicks and passed to Bloc. An event may contain some additional data.

2. States

State is part of application state. It is the output of Bloc. When the state changes, the UI component will be notified and based on the current state, it will re-render.


Changing from one state to another is called transition. It includes the next current state, event, and state.


  • A Bloc must extend the base class Bloc of the core bloc package.
  • A Bloc must define the initial state.
  • Must implement the function mapEventToState . This function takes the input event as an argument. It returns the output of the stream of the new state .
  • To access the current state of the block, we can use the currentState property.
  • A block must have a dispatch method. Dispatch receives an event and triggers mapEventToState . Dispatch can be invoked in the presentation class in the block.
  • onTransition is called before state bloc is updated.
  • onError can override to detect bloc exception.

Here are some demo codes about Bloc:

Step 1: Create Events

Step 2: Create State

Step 3: Create Bloc

Step 4: Create BlocProvider in main.dart

Step 5: Using state Bloc and dispatch events

This article I have written the shortest and easiest to understand about Bloc and how to use it. Thank you for reading my article 😄


Share the news now

Source : Viblo