What You'll Build in This Flutter BLoC Tutorial
This Flutter BLoC tutorial for beginners builds a small Habit Tracker: load a list of study habits, add new ones, tick them off, count glasses of water and show a SnackBar when you finish a habit. You will use both styles of the flutter_bloc package, a Cubit for the simple counter and a Bloc with events for the habit list, and finish with unit tests.
"Flutter bloc tutorial for beginners" and "flutter bloc cubit tutorial" are two of the most searched Flutter learning phrases right now, and flutter_bloc 9.1.2 was published on pub.dev this week. If you already did the Riverpod tutorial, this lesson shows the other popular approach to Flutter state management, so you can compare them on a similar app.
Prerequisites
- Flutter installed and comfortable running
flutter run. - Basic widgets,
StatelessWidget,StatefulWidgetandListView.builder. The setState todo app tutorial covers them. - Dart 3 basics such as classes,
switchexpressions and async/await. Our Dart cheat sheet is a quick refresher.
Bloc vs Cubit in One Minute
- Cubit: the UI calls a method such as
drink(), and the Cubit callsemit(newState). Little code, ideal for simple state. - Bloc: the UI adds an event such as
HabitToggled('1'), and the Bloc handles it withon<HabitToggled>. More code, but every change has a named cause you can log and test. - Both hold one current
state, emit new states over time, and work with the same widgets:BlocProvider,BlocBuilder,BlocListenerandBlocConsumer.
Build the Habit Tracker with flutter_bloc Step by Step
1 Create the project and add the packages
Create a new app and add flutter_bloc, plus bloc_test as a dev dependency for step 10. Like our Riverpod lesson, this one uses the standalone material_ui package from Flutter 3.50 (see the material_ui migration guide). On an older Flutter, skip it and import package:flutter/material.dart instead.
flutter create habit_tracker
cd habit_tracker
flutter pub add flutter_bloc
flutter pub add material_ui
flutter pub add dev:bloc_test
2 Your first Cubit: a water counter
A Cubit is the simplest kind of bloc. It holds one state value and exposes methods. Each method calls emit with the new state, and every widget listening to the Cubit gets it.
// lib/water_cubit.dart
import 'package:flutter_bloc/flutter_bloc.dart';
/// Counts glasses of water. The state is just an int.
class WaterCubit extends Cubit<int> {
WaterCubit() : super(0); // initial state
void drink() => emit(state + 1);
void reset() => emit(0);
}
3 Add a model and a repository
The model is immutable: to change a habit you create a copy. The repository hides where data comes from, so the Bloc can be tested with fake data later.
// lib/habit.dart
class Habit {
const Habit({required this.id, required this.title, this.done = false});
final String id;
final String title;
final bool done;
Habit copyWith({bool? done}) =>
Habit(id: id, title: title, done: done ?? this.done);
}
// lib/habit_repository.dart
import 'habit.dart';
/// Pretends to load habits from a server or database.
class HabitRepository {
Future<List<Habit>> fetchHabits() async {
await Future<void>.delayed(const Duration(milliseconds: 600));
return const [
Habit(id: '1', title: 'Revise 20 flashcards'),
Habit(id: '2', title: 'Solve 5 maths problems'),
];
}
}
4 Describe events and states with sealed classes
A Bloc receives events (what happened) and emits states (what the UI should show). Dart 3 sealed classes let the compiler check that your UI handles every state.
// lib/habits_event.dart
sealed class HabitsEvent {
const HabitsEvent();
}
final class HabitsRequested extends HabitsEvent {
const HabitsRequested();
}
final class HabitAdded extends HabitsEvent {
const HabitAdded(this.title);
final String title;
}
final class HabitToggled extends HabitsEvent {
const HabitToggled(this.id);
final String id;
}
// lib/habits_state.dart
import 'habit.dart';
sealed class HabitsState {
const HabitsState();
}
final class HabitsLoading extends HabitsState {
const HabitsLoading();
}
final class HabitsLoaded extends HabitsState {
const HabitsLoaded(this.habits);
final List<Habit> habits;
int get doneCount => habits.where((h) => h.done).length;
}
final class HabitsFailure extends HabitsState {
const HabitsFailure(this.message);
final String message;
}
5 Write the Bloc
Register one handler per event with on<Event>. Handlers can be async, and they always emit a new state object instead of changing the old one.
// lib/habits_bloc.dart
import 'package:flutter_bloc/flutter_bloc.dart';
import 'habit.dart';
import 'habit_repository.dart';
import 'habits_event.dart';
import 'habits_state.dart';
class HabitsBloc extends Bloc<HabitsEvent, HabitsState> {
HabitsBloc(this._repository) : super(const HabitsLoading()) {
on<HabitsRequested>(_onRequested);
on<HabitAdded>(_onAdded);
on<HabitToggled>(_onToggled);
}
final HabitRepository _repository;
Future<void> _onRequested(
HabitsRequested event,
Emitter<HabitsState> emit,
) async {
emit(const HabitsLoading());
try {
final habits = await _repository.fetchHabits();
emit(HabitsLoaded(habits));
} catch (_) {
emit(const HabitsFailure('Could not load your habits.'));
}
}
void _onAdded(HabitAdded event, Emitter<HabitsState> emit) {
final current = state;
if (current is! HabitsLoaded) return;
final habit = Habit(
id: DateTime.now().microsecondsSinceEpoch.toString(),
title: event.title,
);
emit(HabitsLoaded([...current.habits, habit])); // a new list
}
void _onToggled(HabitToggled event, Emitter<HabitsState> emit) {
final current = state;
if (current is! HabitsLoaded) return;
emit(HabitsLoaded([
for (final h in current.habits)
h.id == event.id ? h.copyWith(done: !h.done) : h,
]));
}
}
6 Provide the repository, Cubit and Bloc
RepositoryProvider makes the repository available to everything below it. MultiBlocProvider creates both blocs, and ..add(const HabitsRequested()) starts loading as soon as the Bloc is created. BlocProvider closes the blocs for you when they are removed from the tree.
// lib/main.dart
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:material_ui/material_ui.dart';
import 'app_bloc_observer.dart';
import 'habit_repository.dart';
import 'habits_bloc.dart';
import 'habits_event.dart';
import 'habits_screen.dart';
import 'water_cubit.dart';
void main() {
Bloc.observer = const AppBlocObserver(); // step 9
runApp(
RepositoryProvider<HabitRepository>(
create: (_) => HabitRepository(),
child: const HabitApp(),
),
);
}
class HabitApp extends StatelessWidget {
const HabitApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<WaterCubit>(create: (_) => WaterCubit()),
BlocProvider<HabitsBloc>(
create: (context) => HabitsBloc(context.read<HabitRepository>())
..add(const HabitsRequested()),
),
],
child: MaterialApp(
title: 'Habit Tracker',
theme: ThemeData(colorSchemeSeed: Colors.teal),
home: const HabitsScreen(),
),
);
}
}
7 Build the screen with BlocBuilder
BlocBuilder rebuilds from the Bloc's state, and a Dart switch expression draws each state. context.read sends events from callbacks; context.select rebuilds only when the selected value changes.
// lib/habits_screen.dart
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:material_ui/material_ui.dart';
import 'habits_bloc.dart';
import 'habits_event.dart';
import 'habits_state.dart';
import 'water_cubit.dart';
class HabitsScreen extends StatelessWidget {
const HabitsScreen({super.key});
@override
Widget build(BuildContext context) {
// Rebuild this widget only when the water count changes.
final glasses = context.select((WaterCubit cubit) => cubit.state);
return Scaffold(
appBar: AppBar(title: Text('Habits ยท $glasses glasses of water')),
body: Column(
children: [
const AddHabitBar(),
Expanded(
child: BlocBuilder<HabitsBloc, HabitsState>(
builder: (context, state) {
return switch (state) {
HabitsLoading() =>
const Center(child: CircularProgressIndicator()),
HabitsFailure(:final message) => Center(
child: TextButton(
onPressed: () => context
.read<HabitsBloc>()
.add(const HabitsRequested()),
child: Text('$message Tap to retry.'),
),
),
HabitsLoaded(:final habits) => ListView.builder(
itemCount: habits.length,
itemBuilder: (context, index) {
final habit = habits[index];
return CheckboxListTile(
title: Text(habit.title),
value: habit.done,
onChanged: (_) => context
.read<HabitsBloc>()
.add(HabitToggled(habit.id)),
);
},
),
};
},
),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => context.read<WaterCubit>().drink(),
icon: const Icon(Icons.local_drink),
label: const Text('Drink water'),
),
);
}
}
class AddHabitBar extends StatefulWidget {
const AddHabitBar({super.key});
@override
State<AddHabitBar> createState() => _AddHabitBarState();
}
class _AddHabitBarState extends State<AddHabitBar> {
final _controller = TextEditingController();
void _submit() {
final text = _controller.text.trim();
if (text.isEmpty) return;
context.read<HabitsBloc>().add(HabitAdded(text));
_controller.clear();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(12),
child: TextField(
controller: _controller,
decoration: const InputDecoration(
labelText: 'New habit',
border: OutlineInputBorder(),
),
onSubmitted: (_) => _submit(),
),
);
}
}
8 Show a SnackBar with BlocListener
Things that must happen once per change, like a SnackBar or navigation, belong in a BlocListener, not in builder. listenWhen filters which changes trigger it. If you need both in one place, BlocConsumer takes a listener and a builder.
// In HabitsScreen, wrap the BlocBuilder with a BlocListener:
BlocListener<HabitsBloc, HabitsState>(
listenWhen: (previous, current) =>
previous is HabitsLoaded &&
current is HabitsLoaded &&
current.doneCount > previous.doneCount,
listener: (context, state) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Nice! Habit done.')),
);
},
child: BlocBuilder<HabitsBloc, HabitsState>(
// ...the same builder as before
),
)Tap a checkbox: the Bloc emits a new HabitsLoaded state with that habit marked done, and the SnackBar appears once.
9 Log every change with a BlocObserver
A BlocObserver sees every state change and error in the app, which makes debugging much easier. Set it once in main() (already done in step 6).
// lib/app_bloc_observer.dart
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class AppBlocObserver extends BlocObserver {
const AppBlocObserver();
@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
debugPrint('${bloc.runtimeType}: $change');
}
@override
void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
debugPrint('${bloc.runtimeType} error: $error');
super.onError(bloc, error, stackTrace);
}
}
10 Test the Cubit and the Bloc with bloc_test
blocTest builds a bloc, runs an action and checks the states it emits. seed starts from a given state and wait gives async handlers time to finish. Run it with flutter test.
// test/habits_test.dart
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:habit_tracker/habit.dart';
import 'package:habit_tracker/habit_repository.dart';
import 'package:habit_tracker/habits_bloc.dart';
import 'package:habit_tracker/habits_event.dart';
import 'package:habit_tracker/habits_state.dart';
import 'package:habit_tracker/water_cubit.dart';
void main() {
blocTest<WaterCubit, int>(
'emits [1, 2] when drink is called twice',
build: WaterCubit.new,
act: (cubit) => cubit
..drink()
..drink(),
expect: () => [1, 2],
);
blocTest<HabitsBloc, HabitsState>(
'loads habits from the repository',
build: () => HabitsBloc(HabitRepository()),
act: (bloc) => bloc.add(const HabitsRequested()),
wait: const Duration(seconds: 1),
// HabitsLoading is not emitted again: it equals the initial state.
expect: () => [
isA<HabitsLoaded>().having((s) => s.habits.length, 'length', 2),
],
);
blocTest<HabitsBloc, HabitsState>(
'toggles a habit',
build: () => HabitsBloc(HabitRepository()),
seed: () => const HabitsLoaded([Habit(id: '1', title: 'Read')]),
act: (bloc) => bloc.add(const HabitToggled('1')),
expect: () => [
isA<HabitsLoaded>().having((s) => s.doneCount, 'doneCount', 1),
],
);
}
How Flutter BLoC Works: Key Ideas
- One-way data flow. Widgets send events or call methods; blocs emit states; widgets rebuild. Widgets never change state directly.
- Equal states are skipped. A bloc does not emit a state that is equal to the current one. That is why the tests expect no second
HabitsLoading, and why you should always build new objects. - read, watch, select.
context.readgets a bloc without listening (use it in callbacks),context.watchrebuilds on every change, andcontext.selectrebuilds only when one value changes. - Events run concurrently by default. Each
on<Event>handler processes events concurrently unless you pass atransformer. The separatebloc_concurrencypackage adds transformers such asdroppableandrestartablefor things like search boxes. - Lint support. flutter_bloc 9.1.2 moved to
bloc_lint0.4, a set of lint rules for common BLoC mistakes that you can add to your own project.
Practice Tasks
- Add a
HabitDeletedevent and a swipe-to-delete gesture withDismissible. - Make
HabitRepository.fetchHabitsthrow an exception and check that the retry button in theHabitsFailurestate works. - Add a
resetbutton for the water count and ablocTestthat checksWaterCubitgoes back to 0.
Flutter BLoC Quiz
Five quick questions on this tutorial.
Frequently Asked Questions
What is BLoC in Flutter?
BLoC (Business Logic Component) is a pattern, and flutter_bloc is the package that implements it. Your UI sends events or calls methods, a Bloc or Cubit runs the logic and emits new states, and widgets such as BlocBuilder rebuild from those states. It keeps business logic out of widgets, so it is easy to test.
What is the difference between Bloc and Cubit?
A Cubit exposes plain methods that call emit, so it has less code. A Bloc receives event objects and handles each with on<Event>, which gives you a full record of what happened and lets you control how events are processed. Start with a Cubit and switch to a Bloc when the flow gets complex.
Is BLoC better than Riverpod or Provider?
None is best for every app. BLoC is strict and event-driven, which many teams like for large apps and testing. Riverpod and Provider need less code for simple state. Pick the one your team understands, and keep logic out of widgets either way.
When should I use BlocListener instead of BlocBuilder?
Use BlocBuilder to draw UI from state; it may run many times. Use BlocListener for one-off actions such as showing a SnackBar, a dialog or navigating, which must run once per state change. BlocConsumer combines both.
Which flutter_bloc version does this tutorial use?
It was checked against flutter_bloc 9.1.2, bloc 9.2.2 and bloc_test 10.0.1, the versions on pub.dev on November 29, 2026.
Sources
- Bloc library documentation (bloclibrary.dev)
- pub.dev: flutter_bloc and its changelog
- pub.dev: bloc
- pub.dev: bloc_test
- Dart docs: sealed classes
Checked November 29, 2026 against flutter_bloc 9.1.2, bloc 9.2.2 and bloc_test 10.0.1 on pub.dev.