Flutter: Why Bloc?

Nut.Lee
odds.team
Published in
2 min readMay 27, 2023

Building a mobile application in 2023, it’s a common scenario to fetch data from different sources and use it to display information or perform calculations.

To simplify the concept, it can be explained like this:

When creating a mobile app, you also need to set up a backend server to work together. Whenever the app needs data, the app will request the data from the backend server.

The mobile app can be divided into two main parts. The first thing is the part that shows the information on the screen (User Interface / UI) and the second one to handles the logic.

Bloc was developed to address this separation:

The purpose of Bloc is to separate the UI from the logic. This brings several benefits:

  1. Reduces repetitive logic code.
  2. Makes the code easier to read and understand.
  3. Prevent issues that may occur when requesting data from an external source, such as making the same request multiple times or handling error responses.

Here’s how Bloc works:

When the UI triggers an action, it’s called an “event.” > When an event occurs, the Bloc starts working on it. > Once the Bloc finishes its task, it emits a “state” as a result.

Flutter and Bloc are used together with a streaming approach. This means that Flutter needs to listen for states emitted by the Bloc, no matter when they happen. When a state is received, Flutter continues its operations accordingly.

In summary, Bloc is a tool that helps developers separate the UI and logic in their code. This makes the code easier to read and makes it easy to find where are codes for screen presentation or codes for logic. Additionally, improves the app’s performance and can help prevent errors that may occur.

--

--