Understanding Bloc in Flutter | The Easiest Guide

01 Mar 2024 | Saheb Singh Understanding Bloc in Flutter | The Easiest Guide

 Building interactive and dynamic user interfaces in Flutter is exciting! But as your app grows, managing application state (data that affects the UI) can become a challenge. Traditional methods like setState can quickly lead to complex code, making it difficult to maintain and test. Here's where Bloc comes in! Bloc is a powerful state management library for Flutter that helps you separate your UI logic from business logic, leading to cleaner, more predictable, and easier-to-test code. This article is a beginner-friendly guide to getting started with Bloc in your Flutter projects. We'll walk you through the core concepts, build a simple example, and provide tips for using Bloc effectively.


What is BLOC?

Well let's talk about the elephant in the room shall we? What is this Bloc anyway? Why has this become one of the must-haves? What happened to the good old setState and Provider seems pretty simple, right? Okat let's break this part by part. BLoC stands for Business Logic Component, which is referring to nothing but a module or a class which holds all our business related code. Now what could be a Business Logic? for example like deciding which api to call, what values to calculate and when to calculate. 

At a very top level, it basically separates the UI code from our business logic. I think we all can agree that bringing unwanted calculations and operations inside the UI code can really harm the code readability which in turn makes the code that much difficult to debug and manage. Let's understand this with a diagram shall we?

You can think of Bloc as a person who will take orders for what to do and will give you the results back, similar to a waiter, no? . Let's say we are building and application which will increase the number on the screen by some logic (could be +1 or multiply by 8) on tap of a button. On the left is our application's UI and it only cares about firing an event and then listening to what our Bloc has to return. Whatever the Bloc returns it displays on the screen. The UI now doesn't care what we are doing with the number! it only cares what it needs to show! That's what we call Business Logic separation.- the whole idea behind the BLoc!


State Management using BLoC

Let's move on the practical aspects of BLoc. How is BLoC implemented in Flutter? How it manages the states? Let's find answer to these questions now. We will be very often using these two terminologies when we talk about bloc. Event,State and Bloc. Lets understand them one by one.

  • Events: These represent user interactions or actions that trigger state changes within your app. Examples include button presses, text input changes, or network requests.
  • States: These represent the different stages or conditions of your app's data at any given time. They hold the information that your UI displays and reacts to.
  • Bloc: This is the heart of Bloc. It's a component that receives events as input, processes them based on your business logic, and emits new states as output.

Let's look into a diagram first to get a basic picture in our heads


+------+         +---------+         +---------+            +----------+
| User | ------> | Event    | ------> | Bloc     | ------> | New State| ------> | UI (BlocBuilder/BlocListener) |
+------+         +---------+         +---------+            +----------+
                      ^                 |                     ^
                      |                 |                     |
                   Processes Event   Emits New State based on  Updates UI based on new state
                      based on Logic   current state and logic


Or as can be seen on the official documentation :


Let's Code:

I think it's enough theory for now. Let's jump into the code and understand how we code a BLoc. Let's take a Login example. Say we want to Login on press of a buton, We will fire an event called DoLogin and based on the credentials, we will have possible states like LoginSucess, LoginError.

Bloc : Bloc is defined by extending Bloc class from the flutter_bloc package.

     Bloc Name             Event Type         State Type
  
        |                      |                |
        ˅                      ˅                ˅
class LoginBloc extends Bloc<LoginEvent, LoginState> {
  LoginBloc () : super(const LoginState()) {
  }
}

 Bloc takes two parameters to function , Event and State, You can think of them as Input,Output respectively. 

Events are what comes inside Bloc, or like an Order, State is what like an Output of what our Bloc was able to obtain. This is will all fall into place, trust me. Let's see how we can create our Events and States. 

Events - 

abstract class LoginEvent {}

class DoLogin extends LoginEvent {}

States - 

abstract class LoginState {}

class LoginIntialState extends LoginState {}

class LoginSuccess extends LoginState {}

class LoginError extends LoginError {}

the growing developer
Hi, my name is Saheb Singh , I am a A Software Engineer by Profession. I love to spread the knowledge I gain.I make tutorial videos on Youtube and write blogs for the same.

More blogs related to Flutter

How to create models in Flutter | Dart? A Beginners Guide

How to create models in Flutter | Dart? A Beginners Guide | Flutter

21 Nov 2024 | Saheb Singh

Models are the core of the data flow in any of the MVC architecture. Learn how to make models in Flutter/Dart in a professional way....

Realtime Database vs Cloud Firestore - Which database to choose ?

Realtime Database vs Cloud Firestore - Which database to choose ? | Flutter

21 Nov 2024 | Saheb Singh

Your Go-to Guide to decide which database to choose and why....

Flutter Tutorial - How to build Beautiful Login Screen with Google Sign - Part I

Flutter Tutorial - How to build Beautiful Login Screen with Google Sign - Part I | Flutter

21 Nov 2024 | Saheb Singh

Let's create a Clean and Materialistic UI Design for Login and see how we can implement google signin using Firebase Auth...

How to fetch data from Internet | Flutter API Integration

How to fetch data from Internet | Flutter API Integration | Flutter

21 Nov 2024 | Saheb Singh

In this video we will learn about fetching data from the Internet. Learn to make API calls from your flutter application...

PageView and PageController | Flutter Tutorial for Beginners

PageView and PageController | Flutter Tutorial for Beginners | Flutter

21 Nov 2024 | Saheb Singh

A complete guide on using PageView and PageController in Flutter....

© copyright 2020. All Rights Reserved.