I’m a visual learner. If you’re anything like me, you like to understand the higher up concepts before diving into details.

I’ve started using Flutter at work and at home. It’s incredible how easy it is to build user interfaces quickly. It’s really great. And with my apps, I heavily rely on the Bloc pattern for state management.

Basics

Bloc relies on three components. An event, a bloc, and a state.

As you can see, an event comes in, and then the bloc determines what state should result. An example might help.

Let’s say the result of some api call, comes in as an event into your bloc.

Within your bloc, you can determine whether or not that result was a success or failure. You can emit the proper state and your UI can react to it.

Flutter Bloc Integration

At this point, you understand bloc. Actually, yeah, it’s that simple! Let’s see how you can actually use it now.

Before that, let us make sure we’re on the same page. Remember, everything is a widget. And it’s put together in a widget tree. Let’s look at a simple example.

In your app, you typically initialize a bloc and give the sub tree access to the bloc with a bloc provider.

After the bloc is provided, every widget can submit events to the bloc. These are typically buttons or text fields that send events to the bloc.

Also, events can be provided by repositories (which can be connected to APIs, Firebase Firestore, and any other business logic). I’ll cover them in a separate post.

Now that the bloc has been initialized and provided, a bloc builder (and other widgets) can give widgets in the sub tree direct access to the bloc’s state.

A bloc builder allows you to change how you build your widgets with the current state. If we zoom in a bit, we can see that different states will affect how a UI is built.

Summary

At this point, I hope you can see how a bloc is initialized, how other widgets and other services can give it events, and how bloc builders can listen and adjust to states of the bloc.

Learn more

To learn more about flutter and bloc (and to get into some actual code), I would highly recommend checking out the package flutter_bloc and its really well made wiki.

Thank you for reading!

Software engineer by day, software engineer by night.