Sub topic 15
Logging every change with BlocObserver
This chapter shows how to watch every state change, event and error from every Cubit and Bloc in an app from one place. It assumes you can write a Cubit and a Bloc, you know what emit does, and you are comfortable with Dart classes and @override. Earlier chapters covered all of that.
Why a global observer
Suppose a screen shows the wrong value. You need to know which Cubit changed, what the old state was, and what caused the change. Without tooling, you would add print calls to each Cubit and remove them later.
A BlocObserver solves this once. It is a class with methods that the bloc library calls for every Cubit and Bloc in the app. You write the logging in one place, and any bloc created later is covered automatically.
An observer is not a place for business logic. It sees every bloc but should never change one. Use it for logging, analytics and crash reporting.
The six hooks
BlocObserver has six methods you can override. Some apply only to a Bloc, because a Cubit has no events.
| Method | Called when | Cubit | Bloc |
|---|---|---|---|
| `onCreate` | A Cubit or Bloc is constructed | Yes | Yes |
| `onEvent` | `add` receives an event | No | Yes |
| `onTransition` | A handler is about to emit a new state | No | Yes |
| `onChange` | The state is about to change | Yes | Yes |
| `onError` | An error is reported | Yes | Yes |
| `onClose` | `close` is called | Yes | Yes |
A Change holds currentState and nextState. A Transition holds the same two states plus the event that caused them. That is why onTransition gives a fuller trace for a Bloc: it tells you the cause, and onChange does not.
A complete observer you can run
This example uses only the bloc package, so you can run it as a plain Dart program. flutter_bloc re-exports the same classes, so the observer works unchanged in a Flutter app.
import 'package:bloc/bloc.dart';
sealed class CounterEvent {}
final class CounterIncremented extends CounterEvent {}
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<CounterIncremented>((event, emit) => emit(state + 1));
}
}
class LoggingObserver extends BlocObserver {
@override
void onCreate(BlocBase<dynamic> bloc) {
super.onCreate(bloc);
print('create ${bloc.runtimeType}');
}
@override
void onEvent(Bloc<dynamic, dynamic> bloc, Object? event) {
super.onEvent(bloc, event);
print('event ${bloc.runtimeType} ${event.runtimeType}');
}
@override
void onTransition(
Bloc<dynamic, dynamic> bloc,
Transition<dynamic, dynamic> transition,
) {
super.onTransition(bloc, transition);
print('transition ${bloc.runtimeType} '
'${transition.currentState} -> ${transition.nextState}');
}
@override
void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
super.onChange(bloc, change);
print('change ${bloc.runtimeType} '
'${change.currentState} -> ${change.nextState}');
}
@override
void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
print('error ${bloc.runtimeType} $error');
super.onError(bloc, error, stackTrace);
}
@override
void onClose(BlocBase<dynamic> bloc) {
super.onClose(bloc);
print('close ${bloc.runtimeType}');
}
}
Future<void> main() async {
Bloc.observer = LoggingObserver();
final bloc = CounterBloc();
bloc.add(CounterIncremented());
await Future<void>.delayed(Duration.zero);
await bloc.close();
}Running it prints:
create CounterBloc
event CounterBloc CounterIncremented
transition CounterBloc 0 -> 1
change CounterBloc 0 -> 1
close CounterBlocThe order matters. onEvent fires as soon as you call add. When the handler emits, onTransition runs first and onChange runs just before the state value is replaced. Every transition therefore produces a change, but a change does not always come with a transition. A Cubit only produces changes.
Always call super in each override. The base implementations are empty today, but calling super keeps your observer correct if the library adds behavior later.
Installing the observer in a Flutter app
Bloc.observer is a static field, so you set it once, before any bloc is created. The natural place is main, before runApp.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class AppBlocObserver extends BlocObserver {
@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);
}
}
void main() {
if (kDebugMode) {
Bloc.observer = AppBlocObserver();
}
runApp(const MaterialApp(home: Scaffold()));
}The kDebugMode check keeps logging out of release builds. The default observer does nothing, so skipping the assignment in release mode costs nothing.
Reporting errors with addError
onError is called when a Cubit or Bloc reports an error. This happens in two ways. An exception thrown inside an event handler is reported automatically. You can also report one yourself with addError.
This second path matters because of the pattern you learned for async state. A try/catch that turns an exception into a failure state handles the error, so the observer never hears about it. If you want it logged or sent to a crash service, report it too:
import 'package:bloc/bloc.dart';
class DownloadCubit extends Cubit<String> {
DownloadCubit(this._download) : super('idle');
final Future<String> Function() _download;
Future<void> start() async {
emit('loading');
try {
emit(await _download());
} catch (error, stackTrace) {
addError(error, stackTrace);
emit('failed');
}
}
}addError calls the Cubit's own onError and then Bloc.observer.onError. It does not change the state or throw, so the UI still gets the failed state it can render.
A Cubit or Bloc can also override onChange and onError itself. This is useful for logic that belongs to one bloc only. The global observer is better for behavior you want everywhere.
Common uses and limits
A global observer fits these jobs well:
- Logging state changes during development.
- Recording events and transitions as analytics breadcrumbs.
- Forwarding
onErrorto a crash reporting service. - Tracking which blocs are alive, by counting
onCreateandonClosecalls. A bloc that is created many times and never closed points to a lifecycle bug.
It also has limits you should plan for:
- One observer only.
Bloc.observerholds a single instance. To combine logging and crash reporting, write one observer that calls both, or one that delegates to a list of handlers. - Everything is reported. Every bloc in the app, including those from packages, goes through the observer. Filter by type when the output gets noisy, for example
if (bloc is! CounterBloc) return;. - State may be sensitive. Printing
changeprints the full state object. A state holding tokens, emails or form text will leak that data into logs. Log the bloc type and status, not whole states, in anything beyond local debugging. - Keep it fast. The observer runs synchronously inside
emit. Slow work there slows every state change. Send heavy work, such as network calls to an analytics service, to a queue. - Tests inherit it. The static field persists across tests in one file. If one test sets an observer, later tests still use it. Reset it with
Bloc.observer = BlocObserver();insetUportearDownif that matters.
Summary
A BlocObserver is installed once with Bloc.observer and receives onCreate, onEvent, onTransition, onChange, onError and onClose for every Cubit and Bloc. Only Blocs get onEvent and onTransition. Errors you handle with try/catch stay invisible to the observer unless you also call addError. Keep the observer fast, guard it with kDebugMode, and be careful about what state data you write to logs.
Exercise
Your TodosCubit catches every exception from the repository and emits a failure state. Your crash reporter is wired into BlocObserver.onError, but it never receives repository errors. Why, and what is the smallest change that fixes it?
Show answer
The catch block handles the exception, so nothing is thrown or reported, and onError is never called. Add addError(e, stackTrace) inside the catch block (catching catch (e, stackTrace)) before or after emitting the failure state. addError calls the Cubit's onError and then Bloc.observer.onError without changing the state, so the UI still shows the failure state.
Exercise
A CounterBloc receives add(CounterIncremented()) once and the handler emits state + 1. Which observer methods are called, and in what order? Which of them would a CounterCubit calling emit(state + 1) trigger?
Show answer
For the Bloc: onCreate (at construction), then onEvent, onTransition, onChange, and later onClose when it is closed. A Cubit has no events or transitions, so it triggers only onCreate, onChange and onClose.