Sub topic 3
Your first Cubit: state, emit and methods
This chapter builds a Cubit from scratch and explains what happens when it changes state. It assumes you know Dart classes, generics, and the idea of immutable state from the previous chapter. It also assumes you have seen Dart Streams. The code here is plain Dart, so you can run it without a widget tree. Connecting a Cubit to widgets is the next chapter's job.
What a Cubit is
A Cubit is an object that holds one piece of state and exposes methods that replace it. It has three parts:
- State: a single value of type
State, readable through thestategetter. - Initial state: the value you pass to
super(...)in the constructor. emit: the only way to replace the state. A Cubit's public methods callemitwith a new value.
The Cubit<State> class comes from the bloc package. The flutter_bloc package re-exports it, so one import is enough in a Flutter app. For the pure Dart examples below, add bloc to pubspec.yaml and import package:bloc/bloc.dart.
The smallest useful Cubit
import 'package:bloc/bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}The type argument int is the state type. super(0) sets the initial state, so state is never null or uninitialized. Each method reads the current state, computes the next value, and passes it to emit.
Keep state transitions inside methods. The outside world should never compute a new state and push it in. It should call increment() and let the Cubit decide what that means. This is what moves business logic out of widgets.
Watching emit work
Run this to see the order in which things happen:
import 'package:bloc/bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
@override
void onChange(Change<int> change) {
super.onChange(change);
print('onChange: $change');
}
}
Future<void> main() async {
final cubit = CounterCubit();
final subscription = cubit.stream.listen((value) {
print('stream: $value');
});
print('before: ${cubit.state}');
cubit.increment();
print('after: ${cubit.state}');
await Future<void>.delayed(Duration.zero);
await subscription.cancel();
await cubit.close();
}The output is:
before: 0
onChange: Change { currentState: 0, nextState: 1 }
after: 1
stream: 1Two details matter here:
stateandonChangeupdate synchronously. By the timeincrement()returns,cubit.stateis already1.- The stream delivers the value asynchronously, on a later microtask. That is why the example awaits
Future<void>.delayed(Duration.zero)before cancelling the subscription. Without it, thestream: 1line may never print.
The stream also does not replay the initial state. A listener that subscribes at time zero sees only later emissions. Flutter's BlocBuilder handles this by reading state for its first build, which you will see in the chapter on rebuilding the UI.
What emit does internally
The equality check is the part that surprises people. emit compares the new value with the current one using ==. If they are equal, nothing happens: no onChange, no stream event, and so no rebuild. The check applies after the Cubit has emitted at least once. The first emission always goes through, even if it equals the initial state.
For int, == compares values, so emit(state) is a no-op. For your own state classes, == is reference equality unless you override it. That is why the previous chapter used Equatable.
A Cubit with a state class
Counters are simple, so here is a Cubit that uses a real state class. It uses Equatable and copyWith as in the previous chapter, and it adds a bounded counter with logic in the method:
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
class CartState extends Equatable {
const CartState({this.items = const [], this.limit = 3});
final List<String> items;
final int limit;
bool get isFull => items.length >= limit;
CartState copyWith({List<String>? items, int? limit}) {
return CartState(
items: items ?? this.items,
limit: limit ?? this.limit,
);
}
@override
List<Object?> get props => [items, limit];
}
class CartCubit extends Cubit<CartState> {
CartCubit() : super(const CartState());
void add(String item) {
if (state.isFull) return;
emit(state.copyWith(items: [...state.items, item]));
}
void clear() => emit(state.copyWith(items: const []));
}
Future<void> main() async {
final cart = CartCubit();
cart.stream.listen((s) => print(s.items));
cart
..add('apple')
..add('pear')
..add('plum')
..add('fig'); // ignored: the cart is full
await Future<void>.delayed(Duration.zero);
await cart.close();
}This prints [apple], [apple, pear] and [apple, pear, plum]. The fourth call returns before it reaches emit, so the stream sees only three events.
Notice what the method does. It checks a rule (isFull), builds a new list with the spread operator, and emits a new CartState. It never modifies state.items directly.
Common errors
Mutating the state instead of replacing it
This looks reasonable and does not work:
void addBroken(String item) {
state.items.add(item); // mutates the existing list
emit(state); // same object, so == is true, emit ignores it
}The list changed, but emit receives the very same state object. It is equal to itself, so no event fires and the UI does not update. The fix is the pattern used in CartCubit.add: create a new list and a new state object. Declaring state fields final and defaulting to const [] helps. In a const list, add throws at runtime, so the bug surfaces immediately.
Emitting after close
Once close() has run, emit throws a StateError with the message "Cannot emit new states after calling close". This usually appears when an async method finishes after the Cubit was disposed, for example after the user left the screen. Inside async methods, check isClosed before emitting:
Future<void> loadLater() async {
await Future<void>.delayed(const Duration(seconds: 1));
if (isClosed) return;
emit(state.copyWith(items: const ['loaded']));
}The async chapter returns to this in a fuller form.
Calling emit from outside the Cubit
emit is marked @protected. The analyzer warns if you call cubit.emit(...) from outside the class. Treat that warning as an error. If outside code can emit arbitrary states, you lose the one place where the rules live.
Forgetting to call super.onChange
When you override onChange, call super.onChange(change). Skipping it breaks the link to the global BlocObserver, which the observer chapter covers.
Choosing the state type
A Cubit's state type should match the complexity of what it models:
| Situation | State type | Reason |
|---|---|---|
| One number, flag or string | The primitive itself | Built-in `==`, no class needed |
| Several related fields | A class with `Equatable` and `copyWith` | Value equality and cheap updates |
| Mutually exclusive screens | A sealed class hierarchy or a status enum | The compiler or a switch can check each case |
Starting with a primitive is fine. Changing Cubit<int> to Cubit<CounterState> later is a small refactor, because the methods already hold all the logic.
Lifecycle in brief
A Cubit is created, used, and then closed. Creating one allocates a broadcast StreamController. Closing it releases the controller, and after that the stream completes and emit throws. In a Flutter app you rarely call close() yourself, because BlocProvider does it when the widget leaves the tree. In plain Dart code, such as tests and scripts, you are responsible for it.
Summary of the working model
- A Cubit owns one immutable
statevalue and starts from the value passed tosuper. - Public methods compute the next state and call
emit. emitupdatesstatesynchronously, skips equal values, and pushes to a broadcast stream asynchronously.- Always build a new state object. Never change the old one.
- After
close,emitthrows, so guard async work withisClosed.
Exercise
A Cubit<List<int>> has the method void add(int n) { state.add(n); emit(state); }. The list is mutable. After calling add(5), cubit.state contains 5, but a stream listener never receives an event. Why, and how do you fix it?
Show answer
The method mutates the existing list and then emits that same list object. emit compares the new value with the current state using ==. A List compares by reference, so the same object is equal to itself, and emit returns without notifying anyone. The state value changed in place, but no event fired. Fix it by emitting a new list: void add(int n) => emit([...state, n]);.