Sub topic 13
Under the hood: state as a Stream
Assume you know Dart Streams, async and await, and basic Flutter widget lifecycles. This chapter explains how Cubit and Bloc deliver state changes to widgets.
A Cubit has two related views of state:
stateis the current value. Code can read it synchronously.streamis a sequence of future state values. Code can subscribe to it.
Calling emit updates the current state and adds the new value to the stream. Any active listeners can then react. A stream does not automatically replay old values, so a new raw listener receives future emissions, not the complete history.
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
}
Future<void> main() async {
final cubit = CounterCubit();
final receivedStates = <int>[];
final subscription = cubit.stream.listen(receivedStates.add);
cubit.increment();
cubit.increment();
// Allow the stream listener to receive the values.
await Future<void>.delayed(Duration.zero);
print(cubit.state); // 2
print(receivedStates); // [1, 2]
await subscription.cancel();
await cubit.close();
}The Cubit remains the owner of the current value. The subscription only observes changes. Reading cubit.state does not create a subscription.
How Flutter uses the stream
BlocBuilder subscribes to the state stream and schedules widget rebuilds when a new state arrives. BlocListener uses the same stream for one-time effects, such as navigation or a SnackBar. BlocSelector also subscribes, but rebuilds only when its selected value changes.
A Bloc has an additional event stream internally. Calling add places an event into that stream. An event handler processes the event and emits values into the same kind of state stream exposed by BlocBase.
Stream-related gotchas
A state stream is not a state history or a persistence mechanism. If an app must restore state after a restart, use persistence such as HydratedBloc rather than relying on a subscription.
Do not create manual subscriptions in build. Flutter can call build many times, which would create duplicate listeners. Prefer BlocBuilder, BlocListener, or a lifecycle method such as initState. Always cancel subscriptions that your code owns.
A provider that creates a Cubit or Bloc normally closes it when the provider is removed. If you pass an existing instance with BlocProvider.value, the caller that created the instance remains responsible for its lifetime.
Exercise
Why does a raw subscription to cubit.stream not receive the Cubit's current state immediately?
Show answer
The stream delivers future emissions, while the current snapshot is available separately through cubit.state.