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.

Event, Bloc, and 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.

An API request comes in and it can produce one of two states. Your bloc decides.

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.

How widgets in a tree might get mapped to an app. Super simplified.

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

Every node under the bloc provider has access to it.

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.

Widgets submitting 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.

Api results can come back as an event.

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 receiving 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.