Start a Project

Flutter: State Management using BloC Pattern

Why do we use BloC Pattern ?

It is a Design Pattern and It stands for Business Logic Component. So we can use the Bloc Pattern whenever we need to manage the state of the UI and have to update it automatically when data changes.

You may also check our Flutter app development company page

There should be a bloc in between the data layer and UI because this Bloc creates a connection between the data layer and UI which consequently manages the state of the UI accordingly.

Below all three images will change when we, clicking on the Change Image button as the input event changes.

How to use this pattern

Let’s create a program that will change the UI image as we click on the Change Image button.

Bloc does the process of mapping events to the state.
In this project, we initially provide the 0 value as input to the event to show a default image on the screen.

On pressing the Change Image button, we calculate the value which is increased by one in the block, and use check on button press and then send event according to the condition.

We need to create three files in our project:

1 . Main. dart

2 . HomeScreen

3 . ChangeImage 

Now first of all add the package to pubspec.yaml file

Let’s Check Implementation in Main.dart

From the root of the application, we provide the initial value to the change image class. And make Ui class as a child of BlocProvider

Now Check Implementation in HomeScreen

In the below code, we are doing the UI part in which we are providing the automatically updated input on the button click which eventually results in updating the UI automatically.

And BlocBuilder is used to show changes that will counter from bloc file along with this it also manages state as events changed.

Let’s Check Implementation in ChangeImage

And this is the bloc part of the project where events are taken as input and update the state accordingly and we will be using the switch to check events from the input.

I hope this blog will help you to learn about Bloc Pattern and you will be able to implement it.

Happy Learning ✍️

Reference Links:
https://pub.dev/packages/flutter_bloc

Exit mobile version