This package abstracts reactive aspects of the pattern allowing developers to focus on converting events into states.

Let’s start by defining those terms…

Glossary

Events are the input to a Bloc. They are commonly UI events such as button presses. Events are dispatched and converted to States .

States are the output of a Bloc. Presentation components can listen to the stream of states and redraw portions of themselves based on the given state (see BlocBuilder for more details).

Transitions occur when an Event is dispatched after mapEventToState has been called but before the bloc’s state has been updated. A Transition consists of the currentState , the event which was dispatched, and the nextState .

Now that we understand events and states we can take a look at the Bloc API.

Bloc API

mapEventToState is a method that must be implemented when a class extends Bloc . The function takes the incoming event as an argument. mapEventToState is called whenever an event is dispatched by the presentation layer. mapEventToState must convert that event into a new state and return the new state in the form of a Stream which is consumed by the presentation layer.

dispatch is a method that takes an event and triggers mapEventToState . dispatch may be called from the presentation layer or from within the Bloc (see examples) and notifies the Bloc of a new event .

initialState is the state before any events have been processed (before mapEventToState has ever been called). initialState is an optional getter. If unimplemented, initialState will be null .

transform is a method that can be overridden to transform the Stream<Event> before mapEventToState is called. This allows for operations like distinct() and debounce() to be used.

onTransition is a method that can be overridden to handle whenever a Transition occurs. A Transition occurs when a new Event is dispatched and mapEventToState is called. onTransition is called before a bloc’s state has been updated. It is a great place to add bloc-specific logging/analytics.

Let’s create a counter bloc!

Counter Bloc Implementation

In order to create a Bloc, all we need to do is:

Define our events and states

Extend Bloc

Override initialState and mapEventToState .

In this case our events are CounterEvents and our states are integers .

Our CounterBloc converts CounterEvents to integers.

We can notify out CounterBloc of events by calling dispatch like so:

In order to observe state changes ( Transitions ) we can override onTransition .

Now every time we dispatch a CounterEvent our Bloc will respond with a new integer state and we will see a transition logged to the console.