...

/

Putting BLoC Concepts to Use

Putting BLoC Concepts to Use

Follow step-by-step instructions to implement a counter app using the BLoC architecture.

The Flutter counter app is a well-known app. In this app, we have a counter, and when the “+” button is pressed, the counter value increases. When the “-” button is pressed, the counter value decreases. This lesson will use the BLoC pattern to make the counter app. It’s a simple task, but it’s enough to teach us the basics of BLoC.

Press + to interact
Steps to create the counter app using BLoC architecture
Steps to create the counter app using BLoC architecture

Creating the Bloc abstract class

We’ll create the abstract class with a dispose() method, making sure that all the Bloc classes in our app are implementing the dispose() method. This enables us to close the streams and avoid memory leaks.

We start by creating a bloc directory in the lib folder. This directory is the home for all our Bloc classes. Let’s see how an abstract class with a dispose() method is defined.

Press + to interact
// inside lib/bloc/bloc.dart
abstract class Bloc {
void dispose();
}

Creating the CounterBLoc class

Next, we create the CounterBloc class, which handles the logic of the counter app. This class extends the Bloc abstract class we just created, and it has two StreamControllers ...