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β‘οΈ
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.
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.
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.
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
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');
}
}
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.
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());
}
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(),
);
}
}
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);
}
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.
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.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. Iβm excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project. Β
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to peopleβs lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
Weβve had very little-to-no hiccups at allβitβs been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.Β
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork