Bloc pattern for Flutter on the classic counter app example

One more time about BLoC pattern with a classic counter app example for Flutter.

Reading some articles about reactive programming and using BLoC pattern in applications I understood that something is not clear for me. So, today I had one hour free and decided to make a simple example that follows all the rules for BLoC.

Yes, it was written many articles about this pattern, but I couldn’t find clear definition and instructions and always was the question — how to do it right?

The goal is to make it clear for myself and, hopefully, for readers.

So, the definition of this pattern as Google engineers told on youtube:

  1. All outputs are streams.
  2. All inputs are streams.
  3. BLoC is the simple class that moves logic from the interface.

We can use rxdart package or not, the reactivity does not depend on it. As creators rxdart tell — Dart comes with a very decent Streams API out-of-the-box; rather than attempting to provide an alternative to this API, RxDart adds functionality on top of it.

The counter app

We will use a counter app that creates with new Flutter project.

TODO

  1. Take out all logic from widgets.
  2. In class with BLoC we have to receive only streams.

Decision

  1. Just delete all logic and make main widget Stateless, delete setState.
  2. For the displaying counter’s value in two different places use StreamBuilder — this special widget that receives info from streams.

After that, we create a separate class where build BLoC pattern:

  1. All variables and methods are hidden
  2. For receiving and transfer data use streams. To make them visible create getters.

That’s it! We got a fully working ideal BLoC example where we pass and get data with streams. There is no logic in the interface.

In this way we can separate all calculations, data transfers and etc. from the interface. For example, if we want to add different signs to counter that depend on the quantity we can do it inside BLoC. The interface won’t know anything about this.

Note 1: we create class instance CounterBloc counterBloc = CounterBloc(); and after get data from it. If we need this data on different classes (screens) we can use Singleton, Provider, or Inherited widgets patterns.

This app on Github.

Nice coding for everyone!

Next step: Example BloC pattern with tests and Provider and persistent datastore

Flutter & Swift developer and enthusiast