BLoC PatternMedium30 XP3 min read
What is BlocObserver and how do you use it?
TL;DR: BlocObserver is a global hook that intercepts every Bloc/Cubit event, state transition, and error in the app. Override its methods to add logging, analytics, or crash reporting without touching individual blocs.
Full Answer
BlocObserver follows the Observer pattern. Extend it and set Bloc.observer to your implementation before runApp().
- ▸onCreate: A new Bloc/Cubit was instantiated
- ▸onEvent: A Bloc received an event
- ▸onChange: Any Cubit or Bloc emitted a new state
- ▸onTransition: A Bloc completed a (event -> state) transition
- ▸onError: An exception was thrown inside a handler
- ▸onClose: A Bloc/Cubit was closed
Code Examples
dartProduction BlocObserver with Firebase Analytics
Output
// BLOC CREATED: AuthBloc // AuthBloc: LoginEvent -> AuthLoading // AuthBloc: LoginEvent -> AuthAuthenticated
Common Mistakes
- ✗Adding logging inside every bloc's on<> handler — centralize it in BlocObserver instead
- ✗Forgetting to call super.onXxx() in overridden methods
Interview Tip
💡
BlocObserver is the clean architecture answer to 'how do you add logging without coupling blocs to logging?' — it's AOP (aspect-oriented programming) for state management.
#bloc-observer#logging#analytics#debugging