How to use BLoC in flutter

Leonardo Pizio
3 min readJan 23, 2021

--

BLoC stands for Business Logic Component, is used to separate the UI component from the Logic one, just to be more clear, using BLoC you won’t do operations in the file where the UI is, but “behind the scenes”.

But, why i should use BLoC?

It makes the project more testable and structured. When you are doing (or want to do) a bigger, complex app the bloc is best way to go.

BLoC uses streams, you can think of them like a pipeline that can transport every kind of data, from a boolean to a list of Objects. Streams can look very complicated at first, but int this article i’m going to exaplain you how they can be used in a very simple way.

First, i’m going to create a new project so you can follow me from the start; i’m going to name it bloc_t.

Open the project with VSCode or any other IDE that you prefer.

First thing we are going to add rxdart as a dependency to the project.

I’m using the latest version available at the moment, ^0.25.0

And now we are ready to create the app, to show you how it works i’m going to create a simple page with two buttons that changes the backgroundColor of the scaffold.

But first, let’s create the BLoC class, it doesn’t need anything special, it’s just a class.

It’s nothing special, i know

To be effective, we have to create a subject, which is in fact the stream that will manage the state of the page.

It’s normal to make the subject private, so that we can access it only inside the class, as you can see we have an annotation, to solve it we just need to create a ‘getter’ that allows another class to get the stream of the our subject.

And since we can, let’s create the methods that our buttons will call when pressed, to change the stream last item.

Normally the color would be passed as a parameter of a single function, not like i’ve done here

That’s it! This is a fully functional BLoc! Now we only need to implement it in the page.

To do this, we need to wrap our page (or only the widget that we need to rebuild when a new value comes) with a StreamBuilder, like this:

Now we miss only a few steps, we need to say to the StreamBuilder which stream to listen to and of course, we have to instantiate the class, then create an initial value for the StreamBuilder, so our scaffold won’t receive a null value.

To “capture” the color we access the snapshot.data, if we don’t provide an initialData we will have an error(if the stream is empty), this is to be sure that everything goes as planned).

Assign the onPressed callback for the buttons and we’re ready to go!

And here it is the result of our code

--

--

Leonardo Pizio
Leonardo Pizio

No responses yet