Sub topic 10
Single-Subscription and Broadcast Streams, and Closing a StreamController
This chapter assumes you know Dart's async, await and Future. It also assumes you can write a StatefulWidget that uses initState, dispose and setState. You have already seen StreamBuilder read a stream and rebuild on each event. Here you learn what kind of stream you are handing it, and what you must do when you own the StreamController behind it.
Two kinds of stream
A Dart Stream is either single-subscription or broadcast. The kind decides how many listeners are allowed and what happens to events that arrive when nobody is listening.
| Behavior | Single-subscription | Broadcast |
|---|---|---|
| Listeners allowed | One for the stream's whole life | Any number, at any time |
| Events with no listener | Buffered until someone listens | Dropped |
| Listening again after cancel | Not allowed | Allowed |
| Typical sources | `StreamController()`, `Stream.periodic`, `Stream.fromIterable`, file and HTTP reads | `StreamController.broadcast()`, UI events, `stream.asBroadcastStream()` |
| Second `listen` call | Throws `StateError` | Works |
Single-subscription is the default. It suits a sequence that has to be consumed in full and in order, such as the bytes of a file. Broadcast suits events that happen whether or not anyone cares, such as a button press.
The next program is plain Dart with no Flutter. It shows all three behaviors from the table: buffering, the second-listener error, and dropped events.
import 'dart:async';
Future<void> main() async {
// Single-subscription: events added early are buffered.
final single = StreamController<int>();
single.add(1);
single.add(2);
single.stream.listen((v) => print('first listener: $v'));
try {
single.stream.listen((v) => print('second listener: $v'));
} on StateError catch (e) {
print('StateError: ${e.message}');
}
await single.close();
// Broadcast: events with no listener are lost, late listeners miss history.
final broadcast = StreamController<int>.broadcast();
broadcast.add(10); // nobody is listening, so this event is dropped
broadcast.stream.listen((v) => print('early listener: $v'));
broadcast.add(20);
await Future<void>.delayed(Duration.zero);
broadcast.stream.listen((v) => print('late listener: $v'));
broadcast.add(30);
await Future<void>.delayed(Duration.zero);
await broadcast.close();
}The single-subscription part prints first listener: 1 and first listener: 2, then the StateError message. The broadcast part prints early listener: 20, then early listener: 30 and late listener: 30. The value 10 never appears, and the late listener never sees 20.
How StreamBuilder listens
StreamBuilder calls listen once, when its State is created. It cancels that subscription in its own dispose. If a parent rebuild gives it a different Stream object, it cancels the old subscription and listens to the new one. If the parent passes the same object, nothing changes.
This leads to two rules.
- The
Streamobject must stay stable across rebuilds, for the same reason aFuturemust. Create it ininitState, in a field initializer, or in an object that outlivesbuild. - If a
StreamBuildercan leave the tree and come back, a single-subscription stream will throw on the second subscription.
The second rule catches many people. Consider a panel that appears and disappears:
import 'dart:async';
import 'package:flutter/material.dart';
class TogglePanel extends StatefulWidget {
const TogglePanel({super.key});
@override
State<TogglePanel> createState() => _TogglePanelState();
}
class _TogglePanelState extends State<TogglePanel> {
// Single-subscription: the second time the builder subscribes, it throws.
final Stream<int> _ticks =
Stream<int>.periodic(const Duration(seconds: 1), (n) => n);
bool _visible = true;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_visible)
StreamBuilder<int>(
stream: _ticks,
builder: (context, snapshot) => Text('Tick: ${snapshot.data}'),
),
ElevatedButton(
onPressed: () => setState(() => _visible = !_visible),
child: const Text('Toggle'),
),
],
);
}
}Tapping Toggle twice removes the builder, which cancels the subscription. It then adds a new builder, which calls listen again on a stream that was already listened to. Flutter reports a StateError ("Stream has already been listened to").
There are three fixes, and the right one depends on what the stream means:
- Call
.asBroadcastStream()on the stream when the sequence is a live feed and missing events while hidden is fine. - Create a fresh stream each time the widget appears, if each appearance should restart the sequence. Do this in
initStateof a child widget, not inbuild. - Keep the builder in the tree and hide it with
Visibility(maintainState: true, ...)orOffstage.
The life of a controller
You usually get a stream from a library. When you need to push values in yourself, you create a StreamController. The controller has two sides: a sink you write to (add, addError, close) and a stream you read from.
Three details to remember:
- After
close(), callingaddthrows aStateError("Cannot add event after closing").isClosedtells you whether it is safe. - Closing sends a done event to listeners.
StreamBuilderthen reportsConnectionState.done, and the last data stays in the snapshot. close()returns aFuture. On a single-subscription controller with no listener, that future may not complete until someone listens and receives the done event. Do notawaitit insidedispose, which is synchronous anyway. Call it and move on.
Owning a controller in State
A controller belongs to the object whose lifetime matches the stream. In a widget, that is the State. You create the controller once and close it in dispose. The dispose method is the only place Flutter promises to call when the widget is permanently gone.
import 'dart:async';
import 'package:flutter/material.dart';
class MessageBox extends StatefulWidget {
const MessageBox({super.key});
@override
State<MessageBox> createState() => _MessageBoxState();
}
class _MessageBoxState extends State<MessageBox> {
final StreamController<String> _messages =
StreamController<String>.broadcast();
late final Timer _timer;
int _n = 0;
@override
void initState() {
super.initState();
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
// Guard against late callbacks that fire after close.
if (!_messages.isClosed) {
_messages.add('Message ${++_n}');
}
});
}
@override
void dispose() {
_timer.cancel();
_messages.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return StreamBuilder<String>(
stream: _messages.stream,
initialData: 'No messages yet',
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.done) {
return Text('Closed. Last: ${snapshot.data}');
}
return Text(snapshot.data ?? '');
},
);
}
}The order in dispose matters. Stop the sources that feed the controller first (_timer.cancel()), close the controller, then call super.dispose(). Reversing this can leave a timer firing into a closed controller.
The isClosed guard matters more for asynchronous work you cannot cancel, such as a network callback that returns after the user has left the screen. Check mounted for setState, and check isClosed for controllers.
Choosing between the two for a controller
Use this checklist when you write StreamController(...).
- Exactly one consumer, and it must not miss anything: use the default controller. Events added before the
StreamBuildersubscribes will be delivered. - Several widgets read the same events, or a widget may be rebuilt into a new subscription: use
.broadcast(). - You need the latest value for late subscribers: neither type gives you that. Keep the latest value in a field and pass it as
initialData, or use a state management package built for it.
Broadcast streams carry a trap with initialData. The first frame shows initialData. After that the builder only knows about events delivered once it is subscribed. If your code adds an event in initState before the first build, a broadcast controller drops it, because StreamBuilder has not subscribed yet. A single-subscription controller would have buffered it.
Errors and the snapshot
Calling controller.addError(error) does not close the stream. StreamBuilder gives you a snapshot with hasError true, and it keeps listening. The next normal event produces a snapshot with data and no error. If you want an error to stop the feed, close the controller yourself after adding it.
Errors inside listen callbacks you wrote are a different matter. An exception thrown in the builder function is a rendering error. An exception thrown inside a stream transformation (map, where) becomes a stream error event.
Common mistakes
- Reusing a single-subscription stream across widgets. Each
StreamBuildercallslisten, so two builders on one such stream throw. Use a broadcast stream. - Forgetting
close(). A controller with no listeners is usually garbage collected, but a controller held by a long-lived object keeps its listeners and any buffered events alive. - Adding after close. This comes from delayed callbacks. Cancel the sources, and guard with
isClosedwhere you cannot. - Expecting history from a broadcast stream. Late subscribers get nothing from before they subscribed.
- Closing a controller you did not create. If a parent passed the stream in, the parent owns the controller. Closing it from the child breaks the other consumers.
Exercise
A screen holds final _events = StreamController<int>(); in its State. A StreamBuilder reads _events.stream. A second widget on the same screen also wraps _events.stream in its own StreamBuilder. What happens, and what is the smallest change that fixes it?
Show answer
The second StreamBuilder calls listen on a single-subscription stream that already has a listener, so it throws a StateError ("Stream has already been listened to"). The smallest fix is to create the controller with StreamController<int>.broadcast(), which allows several listeners. The controller should still be closed in dispose.
Exercise
In the MessageBox example, why is _timer.cancel() placed before _messages.close() in dispose, and what does the isClosed check protect against that the timer cancellation does not?
Show answer
Cancelling the timer first stops the source of events, so nothing tries to add to a controller that is about to close. The isClosed check protects against sources you cannot cancel, such as an in-flight network response that arrives after dispose. Adding to a closed controller throws a StateError, and the check avoids that.
Exercise
A broadcast controller receives add(5) in initState. The StreamBuilder that listens to it is built right after and has initialData: 0. What does the first snapshot show, and what would change with a single-subscription controller?
Show answer
With the broadcast controller the event 5 is dropped because no listener existed when it was added, so the builder shows 0 until a later event arrives. With a single-subscription controller the event is buffered and delivered once the builder subscribes, so the builder shows 0 on the first frame and 5 shortly after.