Sub topic 9
Choosing between Cubit and Bloc
This chapter assumes you can write a Cubit with emit, provide it with BlocProvider, and have seen the on<Event> handler syntax. It also assumes you know Dart 3 sealed classes and basic Streams. The goal is a decision you can defend in a code review, not a rule like "always use Bloc".
What the two have in common
Cubit and Bloc both extend BlocBase<State>. They share the following:
- A current
stateand an initial state passed tosuper. - A
streamof states and aclose()method. emit, which ignores a new state that is equal (==) to the current one.- Compatibility with
BlocProvider,BlocBuilder,BlocListener,BlocSelector,bloc_testandBlocObserver.
The widget side of your code does not care which one you wrote. Only the input side differs.
| Aspect | Cubit | Bloc |
|---|---|---|
| Input | Method calls such as `cubit.increment()` | Event objects sent with `bloc.add(event)` |
| Registration | None | One `on<Event>` handler per event type |
| Change record | `Change(currentState, nextState)` | `Transition(currentState, event, nextState)` |
| Extra hooks | `onChange`, `onError` | Also `onEvent` and `onTransition` |
| Concurrency control | Write it yourself | `transformer:` per handler |
| Boilerplate | Low | Higher: an event class per input |
The same feature, written twice
Here is a quantity selector for a shopping cart as a Cubit. The rule is that the quantity never drops below 1.
import 'package:bloc/bloc.dart';
class QuantityCubit extends Cubit<int> {
QuantityCubit() : super(1);
void increment() => emit(state + 1);
void decrement() {
if (state > 1) emit(state - 1);
}
}Here is the same feature as a Bloc. This example imports package:bloc/bloc.dart, so it runs in a plain Dart program with no Flutter dependency. In a Flutter app you would import flutter_bloc instead.
import 'package:bloc/bloc.dart';
sealed class QuantityEvent {}
final class QuantityIncremented extends QuantityEvent {}
final class QuantityDecremented extends QuantityEvent {}
class QuantityBloc extends Bloc<QuantityEvent, int> {
QuantityBloc() : super(1) {
on<QuantityIncremented>((event, emit) => emit(state + 1));
on<QuantityDecremented>((event, emit) {
if (state > 1) emit(state - 1);
});
}
@override
void onEvent(QuantityEvent event) {
super.onEvent(event);
print('event: ${event.runtimeType}');
}
@override
void onTransition(Transition<QuantityEvent, int> transition) {
super.onTransition(transition);
print('${transition.currentState} -> ${transition.nextState} '
'because of ${transition.event.runtimeType}');
}
}
Future<void> main() async {
final bloc = QuantityBloc();
bloc
..add(QuantityIncremented())
..add(QuantityDecremented())
..add(QuantityDecremented());
await Future<void>.delayed(const Duration(milliseconds: 10));
await bloc.close();
}The program prints an event: line for each of the three events. It prints a transition line for the first two events. The third event leaves the state at 1, so no state is emitted and no transition is printed.
The transition line is the main thing a Bloc gives you that a Cubit does not. A Cubit's Change tells you the state went from 2 to 1. A Bloc's Transition also tells you which event caused it. When a bug report says "the quantity went to 1 and I don't know why", the Bloc log answers the question directly.
What you gain with a Bloc
Traceability. Every state change has a named cause. onEvent fires when an event is added, even if the handler later emits nothing. With a BlocObserver you get this for every Bloc in the app. You can also replay a bug by feeding the recorded events into a fresh Bloc and asserting the states.
Concurrency control. A Cubit method is just a Dart method. Two calls to an async method run at the same time, and whichever await finishes last emits last. Take a search box where the user types "fl" and then "flu". If the request for "fl" is slow, its response can arrive after the one for "flu" and overwrite it. In a Cubit you fix this by hand, for example with a request counter that you check after each await. In a Bloc you pass a transformer: on<SearchQueryChanged>(handler, transformer: restartable()) cancels the stale handler. The droppable(), sequential() and concurrent() transformers cover other cases. A later chapter covers them in detail.
An explicit input vocabulary. The sealed event class lists everything that can happen to this feature. Reviewers can read the event list and know the feature's surface. Events can also carry data, such as SearchQueryChanged(query). Events can be created from outside the widget, for example from a stream of platform notifications.
What you pay for it
Every input needs an event class, a registration line and a handler. For a toggle, that is three pieces of code where a Cubit needs one method.
Registration is also not checked by the compiler. The sealed class lets a switch be exhaustive, but on<E> calls are separate statements. If you add QuantityReset and forget on<QuantityReset>, the code compiles and the event changes nothing. A test with bloc_test catches this, so write one test per event.
Cubit has a safety property of its own. emit is @protected, so only the Cubit's own methods should change its state. The public surface is a short list of methods that are easy to find with "go to definition". A Bloc's public surface is add, which accepts any event, and the real list of inputs lives in the event classes.
The decision
The diagram turns the criteria above into a short sequence of questions.
In practice:
- Cubit fits toggles, form fields, theme and locale settings, tab selection, and simple load-once screens such as the
TodosCubit.load()you wrote earlier. If the only async work is one fetch triggered by one button, a Cubit is enough. - Bloc fits search-as-you-type (debounce plus
restartable), "save" buttons that must ignore double taps (droppable), chat or sync features that process inputs in order (sequential), and flows where support needs an audit trail.
Moving from Cubit to Bloc later
The choice is cheap to reverse. Widgets only depend on the state type and on the base-class API, so only the input side changes during a migration. Follow these steps:
- Turn each public Cubit method into an event class.
- Register an
on<Event>handler containing the old method body. - Replace
context.read<X>().method()withcontext.read<X>().add(Event()). - Keep your
BlocBuilder,BlocListenerand state classes as they are.
Start with a Cubit and move to a Bloc when a concrete need appears, such as a race condition you cannot reason about or a missing audit trail. This costs less than writing events up front for every feature.
Common mistakes
- Choosing Bloc for every screen "to be consistent". You get a pile of one-line handlers and no benefit.
- Choosing Cubit and then hand-writing a queue. If you find yourself adding request counters, flags like
_isLoadingguards, orTimerdebounce fields to a Cubit, a Bloc with a transformer says the same thing in one line. - Putting UI concerns in events. Name events after what happened (
QuantityIncremented,SearchQueryChanged), not after widgets (PlusButtonTapped). Event names should survive a UI redesign. - Assuming equal states emit. Both types skip an
emitwhen the new state equals the current one. A Bloc handler that rebuilds the same list will not produce a transition unless the state class has correctprops.
Exercise
A product search screen calls an API on every keystroke. Users report that the result list sometimes shows results for an earlier query than the one in the text field. Should you use a Cubit or a Bloc, and which specific feature of that choice fixes the problem?
Show answer
Use a Bloc. The cause is overlapping async calls: a slow response for an older query arrives after the response for the newer one and overwrites it. Registering the handler with transformer: restartable() from bloc_concurrency cancels the older handler when a new SearchQueryChanged event arrives, so only the latest query can emit. A Cubit could do this with a manual request counter, but the transformer expresses it in one line.
Exercise
You add a new event class QuantityReset to QuantityBloc and dispatch it from a button. The app compiles, but pressing the button does nothing. What is the most likely cause, and how would you catch it automatically?
Show answer
The on<QuantityReset> handler was never registered in the constructor, and the compiler does not check registrations. Write a blocTest that calls bloc.add(QuantityReset()) and expects the reset state. The test fails if no handler exists.