BLoC with Cubit in Flutter: solved exercise
BLoC with Cubit in Flutter: solved exercise
Cubit is the streamlined version of the BLoC pattern: it manages state by emitting typed values without requiring explicit event definitions. It is ideal for UI logic that does not need event histories or complex side effects.
Problem statement
Build a counter with three operations (increment, decrement, reset) using Cubit. The UI must react to every state change automatically without a single setState.
Dependencies
Flutter solution
Expected result
- Counter starts at 0.
- Each button calls a cubit method and the UI rebuilds automatically.
- No
setStateappears anywhere in the screen widget.
Common mistakes
- Creating the cubit inside the widget instead of providing it with
BlocProvider: the cubit is destroyed and recreated on every rebuild. - Using
context.readinsidebuild(it is only safe in callbacks); usecontext.watchorBlocBuilderto observe state. - Emitting the same primitive value: Cubit compares by equality and silently discards duplicates, which can be confusing when state is a mutable object.
When to use Cubit vs BLoC
| Situation | Cubit | BLoC |
|---|---|---|
| Simple state, few operations | ✅ | overkill |
| Event history, audit logging | ❌ | ✅ |
| Complex side effects per event | ❌ | ✅ |
| External streams feeding state | ❌ | ✅ |
Practical use
Cubit is the natural entry point into the BLoC ecosystem. It is used in production apps for forms, shopping carts, filters, user preferences, and any feature-level state that does not need event traceability.
Recommended next exercise
- BLoC with typed events and states in Flutter: solved exercise
- Dependency injection with get_it in Flutter: solved exercise
- Provider in Flutter for global state: solved exercise
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
FAQ
Is Cubit officially part of flutter_bloc?
Yes. Cubit is included in the flutter_bloc package maintained by Felix Angelov and is fully documented.
Can I migrate from Cubit to BLoC without rewriting the UI?
Yes. BlocBuilder works the same with both. Only the class managing the state changes.
Do I need a BlocObserver from day one?
Not required, but adding a global BlocObserver in development to log all state transitions is a highly recommended practice.