Sub topic 8
From Cubit to Bloc: events and on<Event> handlers
This chapter assumes you can write a Cubit with emit, model state with Equatable and copyWith, and use BlocProvider and BlocBuilder. It also assumes Dart 3 sealed classes and basic async/await. The state and repository types (TodosState, TodosStatus, TodosRepository) come from earlier chapters.
What changes when you move from Cubit to Bloc
A Cubit exposes methods. The UI calls cubit.increment(), and the method calls emit. A Bloc exposes no public methods for changing state. The UI describes what happened by creating an event object and passing it to add. The Bloc then decides which new state to emit.
import 'package:flutter_bloc/flutter_bloc.dart';
sealed class CounterEvent {}
final class CounterIncremented extends CounterEvent {}
final class CounterDecremented extends CounterEvent {}
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<CounterIncremented>((event, emit) => emit(state + 1));
on<CounterDecremented>((event, emit) => emit(state - 1));
}
}
// Usage: context.read<CounterBloc>().add(CounterIncremented());Both Cubit and Bloc extend BlocBase. That is why BlocProvider, BlocBuilder, BlocListener and context.read work the same for both. Only the way you trigger a change differs.
| Aspect | Cubit | Bloc |
|---|---|---|
| Trigger | Call a method | Call `add(event)` |
| Type parameters | `Cubit<State>` | `Bloc<Event, State>` |
| Where logic lives | Methods | `on<Event>` handlers |
| What you can observe | State changes (`Change`) | State changes and the event that caused them (`Transition`) |
| Event processing | You write it in the method | Controlled by an event transformer |
Defining events
Events are plain classes. Make them immutable, give each one a name that says what happened (TodosRequested, not LoadTodos), and carry only the data the handler needs. A sealed base class lets the compiler check that you handled every subtype when you use switch.
sealed class TodosEvent {}
final class TodosRequested extends TodosEvent {}
final class TodoAdded extends TodosEvent {
TodoAdded(this.title);
final String title;
}
final class TodoRemoved extends TodosEvent {
TodoRemoved(this.title);
final String title;
}Naming events in the past tense keeps the UI free of business decisions. The widget reports a fact ("the user submitted a title") and the Bloc owns what happens next.
Registering handlers with on<Event>
You register handlers in the Bloc constructor body. Each call to on<E> names an event type and gives a handler that receives the event and an Emitter<State>.
import 'package:flutter_bloc/flutter_bloc.dart';
class TodosBloc extends Bloc<TodosEvent, TodosState> {
TodosBloc(this._repository) : super(const TodosState()) {
on<TodosRequested>(_onRequested);
on<TodoAdded>(_onAdded);
on<TodoRemoved>(_onRemoved);
}
final TodosRepository _repository;
Future<void> _onRequested(
TodosRequested event,
Emitter<TodosState> emit,
) async {
emit(state.copyWith(status: TodosStatus.loading));
try {
final todos = await _repository.fetchTodos();
emit(state.copyWith(status: TodosStatus.success, todos: todos));
} catch (e) {
emit(state.copyWith(
status: TodosStatus.failure,
errorMessage: e.toString(),
));
}
}
void _onAdded(TodoAdded event, Emitter<TodosState> emit) {
emit(state.copyWith(todos: [...state.todos, event.title]));
}
void _onRemoved(TodoRemoved event, Emitter<TodosState> emit) {
emit(state.copyWith(
todos: state.todos.where((t) => t != event.title).toList(),
));
}
}The _onRequested handler has the same loading, success and failure shape as the async Cubit method from the earlier chapter. Only the entry point changed. The handler is a private method, so nothing outside the Bloc can call it directly. The only way in is add.
Three rules apply to handlers:
- Register at most one handler per event type. A second
on<TodoAdded>call fails an assertion in debug mode. - Register handlers inside the constructor, before any event arrives.
- A handler may be synchronous or asynchronous. An
asynchandler can emit several times, as_onRequesteddoes.
The path of one event
Connecting the UI
Providing and building work as with a Cubit. Only the call that triggers work changes. Sending the first event when you create the Bloc is a common pattern.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class TodosPage extends StatelessWidget {
const TodosPage({super.key, required this.repository});
final TodosRepository repository;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => TodosBloc(repository)..add(TodosRequested()),
child: const TodosView(),
);
}
}
class TodosView extends StatelessWidget {
const TodosView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocBuilder<TodosBloc, TodosState>(
builder: (context, state) {
return switch (state.status) {
TodosStatus.initial || TodosStatus.loading =>
const Center(child: CircularProgressIndicator()),
TodosStatus.failure =>
Center(child: Text(state.errorMessage ?? 'Error')),
TodosStatus.success => ListView(
children: [
for (final todo in state.todos)
ListTile(
title: Text(todo),
onTap: () =>
context.read<TodosBloc>().add(TodoRemoved(todo)),
),
],
),
};
},
),
floatingActionButton: FloatingActionButton(
onPressed: () =>
context.read<TodosBloc>().add(TodoAdded('New todo')),
child: const Icon(Icons.add),
),
);
}
}Use context.read inside callbacks, as shown. It does not subscribe the widget to changes.
Emitting from streams
Some handlers react to a stream, such as a database watcher or a socket. Do not loop over the stream and call emit in a callback you detach. Use emit.forEach or emit.onEach, which keep the handler alive until the stream ends.
import 'package:flutter_bloc/flutter_bloc.dart';
sealed class TickerEvent {}
final class TickerStarted extends TickerEvent {}
class TickerBloc extends Bloc<TickerEvent, int> {
TickerBloc() : super(0) {
on<TickerStarted>(_onStarted);
}
Future<void> _onStarted(TickerStarted event, Emitter<int> emit) {
return emit.forEach<int>(
Stream.periodic(const Duration(seconds: 1), (i) => i + 1),
onData: (tick) => tick,
);
}
}The handler's future completes when the stream ends. If the Bloc is closed first, the subscription is cancelled for you.
Edge cases and common errors
- Emitting after the handler finished. If you call
emitafter the handler's future completed, for example inside an un-awaited.thencallback, debug builds throw an assertion error. Alwaysawaitthe work you emit from, or useemit.forEach. - Duplicate states are skipped. If the new state equals the current one (
==), nothing is emitted and no rebuild happens. This is why the Equatablepropslist must include every field. A forgotten field makes real changes look like duplicates. - The initial state is not an emission.
BlocBuilderrenders it, butBlocListenerdoes not fire for it. - Adding to a closed Bloc. Calling
addafterclosethrows aStateError. This often happens when a delayed callback fires after the page has been disposed. - Unhandled exceptions. An exception thrown from a handler is reported to
onError, which you can override on the Bloc or in a global observer. Catching it inside the handler and emitting a failure state, as_onRequesteddoes, is the normal approach. - Ordering. In current versions of the bloc package, events are processed concurrently by default. Two
TodosRequestedevents added quickly can run their handlers at the same time. The concurrency chapter shows how to change that with transformers.
Why the extra structure helps
Because every change passes through add, a Bloc records both the old state and the cause. Override onTransition to see them together, or onEvent to see events as they arrive.
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class LoggingCounterBloc extends CounterBloc {
@override
void onTransition(Transition<CounterEvent, int> transition) {
super.onTransition(transition);
debugPrint('${transition.event} took ${transition.currentState} '
'to ${transition.nextState}');
}
}A Cubit only reports a Change (old state, new state). A Bloc reports a Transition (old state, event, new state), so a log tells you why the state moved.
Exercise
A TodosBloc handler calls fetchTodos().then((todos) => emit(state.copyWith(todos: todos))) without awaiting the future, and the handler returns immediately. What goes wrong in debug mode, and how do you fix it?
Show answer
The handler's future completes before the repository call finishes, so the later emit runs after the handler is done. Debug builds throw an assertion error saying emit was called after an event handler completed. Make the handler async and use final todos = await _repository.fetchTodos(); followed by emit(...), or use emit.forEach when the source is a stream.
Exercise
You add TodoAdded('Buy milk') twice in a row while the list is empty, and you have a typo: TodosState.props is [status, errorMessage], with no todos. The second event's handler runs. Does BlocBuilder rebuild after it, and why?
Show answer
No. After the first event the new state equals the old one under Equatable, because todos is not in props, so emit is skipped and the UI never shows the item. Adding todos to props fixes it. The second event then produces a different list, which is a different state, and it rebuilds.