State Management Using Flutter BloC

Introduction

BloC is like a helper tool for Flutter developers, especially when managing the different states of an app. Imagine “state” as the different situations your app can be in – like loading data, showing content, or handling user interactions.

When building a high-quality app, keeping track of these states becomes really important. Flutter BloC makes this easier by simplifying complex operations, making it easier to manage the app’s state in production-level applications.

Here’s Why Managing State is Crucial:

πŸ”Έ It helps developers know exactly what state the app is in at any given time.
πŸ”Έ It makes testing different scenarios more manageable to ensure the app responds correctly.
πŸ”Έ It allows recording user interactions for making data-driven decisions.
πŸ”Έ It enables efficient development by reusing components across different parts of the app.

BloC was designed to meet all these needs and more, aiming to make state changes predictable and consistent throughout the app.

Choosing the right state management solution among the many available can be overwhelming, as there’s no one-size-fits-all solution. What matters most is selecting the one that suits your team and project needs best.

Flutter BloC aims to bring predictability to state changes by controlling when they can occur and ensuring a consistent method for changing states across the entire application.

At its core, Flutter BloC focuses on separating the business logic from the user interface. In simpler terms, it translates user interactions (events) into different states within the app. This helps maintain clarity and organization, making managing and understanding how the app behaves easier.

User Interaction—-> Events—->States

 

A BLoC takes a stream of events as input and transforms them into a stream of states as output.

BloC or BloC pattern for beginners is hard to understand at beginning unlike Getx. So here I will explain it pretty straght forward and will use a simple counter app example to demonstrate how to use it.

Create a Project and Install it with the Below Command:

flutter pub add flutter_bloc

Here is a list of ideas for the classes you need to know➑️

BloCProvider

Using Flutter BloC, you will create a BloC or Cubit. It takes a create a function. Within this create function, you will call the class that extends Bloc. BloCProvider is usually called from your view. So it’s also the entry point before you use Bloc. It creates the actual BloC.

√ BloCProvider is called from your view.

BloCBulider

BloCBuilder builds a widget when the state is updated. You should wrap the widget using BlocBuilder which updates the widget based on state.

√ BloC Builder is called from your view.

mapEventToState

If you use Flutter BloC, everything is translated as an event from the user side. User interaction in the view is translated as an event to BloC. BloC receives this event and maps them to states. This is where mapEventToState comes into use. So from the name you can easily understand, it converts event to state.

√ mapEventToState should be implemented within the class that extends BloC.

BloCProvider.of<T>

This method allows widgets or your ui to access the BloC instances. You will use BloC instances to show on the UI or make changes to the values properties or fields of BloC.

So this is used for dependency injection. Dependency injection means your app depends on this.

So with this, you can access the instances of BloC.

Project Structure
β”œβ”€β”€ lib
β”‚ β”œβ”€β”€ app.dart
β”‚ β”œβ”€β”€ counter
β”‚ β”‚ β”œβ”€β”€ counter.dart
β”‚ β”‚ β”œβ”€β”€ cubit
β”‚ β”‚ β”‚ └── counter_cubit.dart
β”‚ β”‚ └── view
β”‚ β”‚ β”œβ”€β”€ counter_page.dart
β”‚ β”‚ └── counter_view.dart
β”‚ β”œβ”€β”€ counter_observer.dart
β”‚ └── main.dart
β”œβ”€β”€ pubspec.lock
β”œβ”€β”€ pubspec.yaml

BloCObserver

The first thing we’re going to take a look at is how to create a BloCObserver which will help us observe all state changes in the application.

Let’s create lib/counter_observer.dart:

import 'package:bloc/bloc.dart';

class CounterObserver extends BlocObserver {
@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
print('${bloc.runtimeType} $change');
}
}

main.dart

Next, let’s replace the contents of main.dart with:

import 'package:bloc/bloc.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_counter/app.dart';
import 'package:flutter_counter/counter_observer.dart';

void main() {
Bloc.observer = CounterObserver();
runApp(const CounterApp());
}

We’re initializing the CounterObserver we just created and calling runApp with the CounterApp widget which we’ll look at next.

Upgrade Your Flutter App's State Management with BloC. Ready to Elevate Your Development? Hire Now!

Counter App

Let’s create lib/app.dart:

CounterApp will be a MaterialApp and is specifying the home as CounterPage.

import 'package:flutter/material.dart';
import 'package:flutter_counter/counter/counter.dart';

class CounterApp extends MaterialApp {
const CounterApp({super.key}) : super(home: const CounterPage());
}

Counter Page

Let’s create lib/counter/view/counter_page.dart:

The CounterPage widget is responsible for creating a CounterCubit (which we will look at next) and providing it to the CounterView.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_counter/counter/counter.dart';

class CounterPage extends StatelessWidget {
const CounterPage({super.key});

@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CounterCubit(),
child: const CounterView(),
);
}
}

Counter Cubit

Let’s create lib/counter/cubit/counter_cubit.dart:

The CounterCubit class will expose two methods➑️

increment: adds 1 to the current state
decrement: subtracts 1 from the current state
The type of state the CounterCubit is managing is just an int and the initial state is 0.

import 'package:bloc/bloc.dart';

/class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);

void increment() => emit(state + 1);

void decrement() => emit(state - 1);
}

Counter View

Let’s create lib/counter/view/counter_view.dart:

The CounterView is responsible for rendering the current count and rendering two FloatingActionButtons to increment/decrement the counter.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_counter/counter/counter.dart';

class CounterView extends StatelessWidget {

const CounterView({super.key});

@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: BlocBuilder<CounterCubit, int>(
builder: (context, state) {
return Text('$state', style: textTheme.headline2);
},
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
key: const Key('counterView_increment_floatingActionButton'),
child: const Icon(Icons.add),
onPressed: () => context.read<CounterCubit>().increment(),
),
const SizedBox(height: 8),
FloatingActionButton(
key: const Key('counterView_decrement_floatingActionButton'),
child: const Icon(Icons.remove),
onPressed: () => context.read<CounterCubit>().decrement(),
),
],
),
);
}
}

A BloCBuilder is used to wrap the Text widget in order to update the text any time the CounterCubit state changes. In addition, context.read<CounterCubit>() is used to look-up the closest CounterCubit instance.

Note: Only the Text widget is wrapped in a BloCBuilder because that is the only widget that needs to be rebuilt in response to state changes in the CounterCubit. Avoid unnecessarily wrapping widgets that don’t need to be rebuilt when a state changes.

coma

Conclusion

It’s really important to handle the state of your Flutter apps well. Using Flutter BloC is a fantastic choice because it’s simple to use and understand. Plus, it offers many ways to handle your app’s views and widgets effectively.

For me, I prefer to keep things neat by creating small BloCs. Each one has a specific job, which makes the code cleaner and easier to maintain. However, if your app needs it, you can also use a single big bloc to handle multiple tasks.

In a nutshell, Flutter BloC is flexible. You can choose whether to use lots of small BloCs or a few big ones, depending on what works best for your app.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?