Sub topic 13
Under the hood: state as a Stream
This chapter shows what a Cubit or Bloc does when you call emit. It assumes you can write a Cubit, wire it up with BlocProvider, and read basic Dart Stream code. Knowing the stream behavior explains several surprises: why a state sometimes doesn't rebuild the UI, why a late listener misses values, and why a forgotten subscription leaks.
What every Cubit and Bloc exposes
Both Cubit and Bloc extend BlocBase<State>. The base class gives you two ways to observe state:
stateis the current value, available synchronously at any time.streamis aStream<State>that delivers each new state after it is emitted.
Internally, BlocBase keeps a broadcast StreamController<State>. A broadcast stream allows any number of listeners at once, and it does not buffer values for listeners that subscribe later. That choice produces the behaviors below.
| Behavior | Consequence |
|---|---|
| The initial state is not sent on the stream | A new listener must read `state` to get the starting value |
| Late subscribers miss earlier states | Subscribe before you emit, or read `state` first |
| Delivery is asynchronous | A listener runs after the current synchronous code finishes |
| Equal consecutive states are dropped | `emit` ignores a state that is `==` to the current one |
| Only states travel on the stream | Errors and events are reported through other hooks |
Watching the stream in plain Dart
The bloc package has no Flutter dependency, so you can run this example from the command line with dart run.
import 'package:bloc/bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void setTo(int value) => emit(value);
}
Future<void> main() async {
final cubit = CounterCubit();
cubit.increment(); // emitted before anyone listens
final subscription = cubit.stream.listen((s) => print('stream: $s'));
cubit.setTo(1); // equal to the current state, ignored
cubit.setTo(2);
cubit.setTo(2); // equal again, ignored
await Future<void>.delayed(Duration.zero);
print('state: ${cubit.state}');
await subscription.cancel();
await cubit.close();
}The output is stream: 2 followed by state: 2. The first increment produced state 1 before the listener existed, so the listener never saw it. The calls with unchanged values never reached the stream. The Future.delayed line gives the broadcast controller time to deliver the event before the subscription is cancelled.
The path of one emit
The order of operations inside emit matters when you write observers or debug.
emitchecks whether the new state equals the current one. If it does, nothing happens.onChange(Change(currentState, nextState))runs. At this pointstatestill holds the old value.- The cubit stores the new state, so
statenow returns it. - The new state is added to the stream controller.
- Listeners receive it asynchronously.
A BlocObserver receives the same onChange call, which is why it can log every transition without any code in your Cubits.
How the widgets use the stream
BlocBuilder, BlocListener, BlocConsumer and BlocSelector are wrappers around a stream subscription. The widget reads bloc.state for its first build, subscribes to bloc.stream in initState, and cancels in dispose. When a state arrives, BlocBuilder calls setState, and buildWhen decides whether to skip that rebuild.
This explains a common bug. If you mutate a list inside the state and emit the same instance, == returns true, emit returns early, and nothing rebuilds. Immutable state with Equatable and copyWith, covered earlier, exists to prevent this.
The equality filter also works in your favor. Emitting the same loading state twice, for example, causes one rebuild, not two.
Bloc adds a second stream for events
A Bloc has the same state stream, but it also has an internal stream of events. add(event) pushes onto it, and each on<Event> registration attaches a handler through a transformer. The transformer decides how overlapping events are processed, which is the subject of the concurrency chapter.
Events never appear on bloc.stream. If you want to see them, override onEvent or onTransition, or use a BlocObserver.
Consuming other streams inside a Bloc
A Bloc often needs to react to a stream from outside, such as a timer, a database watcher, or a socket. Use emit.forEach inside a handler. It subscribes, emits a state for each item, and cancels automatically if the handler is cancelled or the Bloc closes.
import 'package:bloc/bloc.dart';
sealed class TickerEvent {}
final class TickerStarted extends TickerEvent {}
class TickerBloc extends Bloc<TickerEvent, int> {
TickerBloc() : super(0) {
on<TickerStarted>(_onStarted);
}
Future<void> _onStarted(TickerStarted event, Emitter<int> emit) {
return emit.forEach<int>(
Stream<int>.periodic(const Duration(seconds: 1), (i) => i + 1).take(5),
onData: (tick) => tick,
);
}
}
Future<void> main() async {
final bloc = TickerBloc();
bloc.stream.listen(print);
bloc.add(TickerStarted());
await Future<void>.delayed(const Duration(seconds: 6));
await bloc.close();
}This prints 1 through 5, one per second. The handler's future completes when the source stream ends. Related helpers are emit.onEach, which runs a callback per item, and await emit.forEach for sequential work.
Subscribing manually and cleaning up
Sometimes a Cubit must follow another Cubit's stream. You own that subscription, so you must cancel it by overriding close.
import 'dart:async';
import 'package:bloc/bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
}
class DoubledCubit extends Cubit<int> {
DoubledCubit(CounterCubit source) : super(source.state * 2) {
_subscription = source.stream.listen((value) => emit(value * 2));
}
late final StreamSubscription<int> _subscription;
@override
Future<void> close() async {
await _subscription.cancel();
return super.close();
}
}The constructor seeds its state from source.state because the stream never replays the current value. Without the close override, the subscription keeps the source cubit's listener list pointing at a dead object, and a later emit would call emit on a closed cubit.
Closing and its failure modes
close() shuts the controller, and isClosed becomes true. BlocProvider calls close for you when it created the instance with create. If you pass an existing instance with BlocProvider.value, you are responsible for closing it.
Other failure modes follow from the stream design:
- Missed initial state. Code that only calls
stream.listennever sees the starting value. Readstatefirst, or usestream.startWith-style logic if you use a stream package. - Lost synchronous expectations. After
emit(x),stateis updated immediately, but listeners run later. Do not assume a widget has rebuilt on the next line. - Errors in the stream.
addErrorand handler exceptions are reported toonErrorand to the observer, not tostreamlisteners as state. Model expected failures as a failure state, as in the async state chapter. - Leaked listeners. Any
stream.listenyou create yourself needs a matchingcancel.
Exercise
A Cubit starts with state == 0. The code calls cubit.emit(5), then subscribes with cubit.stream.listen(print), then calls cubit.emit(5) and cubit.emit(6). What does the listener print, and why?
Show answer
It prints only 6. The first emit(5) happened before the subscription, and a broadcast stream does not replay it. The second emit(5) equals the current state, so emit ignores it. Only emit(6) is a new, distinct state delivered to the listener.
Exercise
Your ProfileCubit listens to authCubit.stream in its constructor and never cancels the subscription. The user logs out, ProfileCubit is closed by its BlocProvider, and then authCubit emits a new state. What goes wrong, and how do you fix it?
Show answer
The leftover listener fires and calls emit on the closed ProfileCubit, which throws a StateError. The fix is to store the StreamSubscription in a field and override close to await _subscription.cancel() before calling super.close().