Sub topic 8
Rendering a Stream with StreamBuilder
This chapter assumes you know Dart async/await and Future, the difference between StatelessWidget and StatefulWidget, and the initState/dispose lifecycle. It also assumes you have read the earlier chapters on AsyncSnapshot, ConnectionState, and FutureBuilder. StreamBuilder follows the same pattern, so this chapter focuses on what is different.
What StreamBuilder does
A Future completes once. A Stream can emit many data events, any number of error events, and then a single done event. StreamBuilder<T> subscribes to a stream and calls your builder function every time something happens. It creates a new AsyncSnapshot<T> for each event and rebuilds only itself, not the surrounding widget.
The working model has four parts:
- The
streamargument is the source.StreamBuildersubscribes to it when the widget is inserted into the tree. - Each event produces a new snapshot, and
builderruns with it. - When the widget is removed from the tree,
StreamBuildercancels its subscription. - If the
streamargument changes to a different object, it cancels the old subscription and subscribes to the new stream.
StreamBuilder never creates or closes the stream. Whoever created the stream owns it.
The snapshot for a stream
The snapshot fields mean slightly different things for streams than for futures.
| Field | Meaning for a stream |
|---|---|
| `connectionState` | `none` (no stream given), `waiting` (subscribed, no event yet), `active` (at least one event arrived and the stream is still open), `done` (the stream closed) |
| `data` | The most recent data event, or `initialData` before the first event |
| `error` | The most recent error event, or `null` |
| `hasData` | `true` if `data` is non-null |
| `hasError` | `true` if `error` is non-null |
An error event does not end the stream. The next data event produces a snapshot with data and no error, so a screen that shows an error can recover without any action from you.
A first StreamBuilder
This widget rebuilds once per second from a periodic stream.
import 'package:flutter/material.dart';
class TickerText extends StatefulWidget {
const TickerText({super.key});
@override
State<TickerText> createState() => _TickerTextState();
}
class _TickerTextState extends State<TickerText> {
final Stream<int> _ticks =
Stream<int>.periodic(const Duration(seconds: 1), (n) => n + 1);
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: _ticks,
initialData: 0,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text('Seconds elapsed: ${snapshot.data}');
},
);
}
}The stream is stored in a field of State, so the same Stream object is passed on every rebuild. Because Stream.periodic never closes, this snapshot stays in the active state after the first tick.
Handling every connection state
A stream that ends needs a branch for done. The next widget counts down from 3 and then closes its stream.
import 'package:flutter/material.dart';
class Countdown extends StatefulWidget {
const Countdown({super.key});
@override
State<Countdown> createState() => _CountdownState();
}
class _CountdownState extends State<Countdown> {
late final Stream<int> _stream = _countdown();
Stream<int> _countdown() async* {
for (var i = 3; i >= 1; i--) {
await Future<void>.delayed(const Duration(seconds: 1));
yield i;
}
}
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: _stream,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return switch (snapshot.connectionState) {
ConnectionState.none => const Text('No stream'),
ConnectionState.waiting => const CircularProgressIndicator(),
ConnectionState.active => Text('T-minus ${snapshot.data}'),
ConnectionState.done => const Text('Liftoff'),
};
},
);
}
}The hasError check comes first because an error can arrive while the connection state is active. If you only switch on the connection state, errors are silently ignored.
On done, snapshot.data still holds the last value (here 1). A stream that loads a list in pages could keep showing that last value on done and not replace it with a message.
Do not create the Stream inside build
The FutureBuilder rule applies here too. A Stream created in build is a new object on every rebuild, so StreamBuilder cancels the old subscription and subscribes again.
// Anti-pattern: a new stream is created on every rebuild.
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: Stream<int>.periodic(const Duration(seconds: 1), (n) => n + 1),
builder: (context, snapshot) => Text('${snapshot.data}'),
);
}If a parent rebuilds this widget more often than once per second, the counter never advances. Each rebuild restarts the periodic timer and the snapshot goes back to waiting. Create the stream once in initState or in a field initializer, as in TickerText above.
A stream that comes from somewhere else, such as a repository or a Firestore query, still needs a stable identity. Calling a method that returns a new stream every time is the same bug. Either store the result in State, or have the repository return the same stream object on each call.
Showing something before the first event: initialData
Without initialData, the first frame has connectionState == waiting and data == null. If you read snapshot.data! without checking, the first frame throws.
With initialData: 0, the first snapshot is still waiting, but hasData is true and data is 0. This lets the first frame render real content. It is useful when a sensible default exists, such as a counter at zero or an empty list.
Keep these points in mind:
initialDatais not an event. It only fills the first snapshot, and it does not change the stream.- Check
hasDatabeforeconnectionStateif you provideinitialData. Awaitingstate with data present should show the data. It should not show a spinner. - If no sensible default exists, leave
initialDataout and render the spinner onwaiting. A fake default can mislead users more than a spinner does.
Single-subscription and broadcast streams
Dart has two kinds of stream, and they behave differently when you listen to them.
| Property | Single-subscription | Broadcast |
|---|---|---|
| Number of listeners | One, for the stream's lifetime | Any number |
| Events with no listener | Buffered until someone listens | Dropped |
| Listening a second time | Throws a `StateError` | Allowed |
| Created by default with | `StreamController<T>()`, `async*` functions | `StreamController<T>.broadcast()` |
A StreamBuilder listens once per subscription, but it can subscribe again. This happens if the widget is removed and re-inserted with the same stream object, or if the stream argument changes back to an earlier stream. A single-subscription stream throws on the second listen. If more than one widget needs the same stream, or one widget may resubscribe, use a broadcast stream.
The cost of a broadcast stream is that nothing is buffered. If the controller adds an event before the StreamBuilder has subscribed, that event is lost. This is the other reason initialData or a stored "last value" is common with broadcast streams.
Owning a StreamController
If your widget creates a StreamController, it must close the controller. Closing it in dispose releases the controller's resources and sends the done event to any listeners.
import 'dart:async';
import 'package:flutter/material.dart';
class CounterPanel extends StatefulWidget {
const CounterPanel({super.key});
@override
State<CounterPanel> createState() => _CounterPanelState();
}
class _CounterPanelState extends State<CounterPanel> {
final StreamController<int> _controller = StreamController<int>.broadcast();
int _count = 0;
@override
void dispose() {
_controller.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
StreamBuilder<int>(
stream: _controller.stream,
initialData: 0,
builder: (context, snapshot) => Text('Count: ${snapshot.data}'),
),
ElevatedButton(
onPressed: () => _controller.add(++_count),
child: const Text('Increment'),
),
],
);
}
}Several details in this example matter:
- The button handler calls
_controller.add, notsetState. Only theStreamBuildersubtree rebuilds, and theColumnand button are untouched. - The controller is a field of
State, so it survives rebuilds ofCounterPanel. StreamBuildercancels its own subscription when it leaves the tree, but it does not close the controller. Withoutclose()indispose, the controller leaks.- Calling
addafterclosethrows aStateError. If a timer or a network callback might fire afterdispose, guard it with_controller.isClosed.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Spinner shows forever after a parent rebuilds | Stream created in `build` | Store the stream in `State` |
| `Bad state: Stream has already been listened to` | Single-subscription stream subscribed twice | Use `.broadcast()`, or create one stream per subscription |
| Null check error on the first frame | `snapshot.data!` while `waiting` | Check `hasData`, or supply `initialData` |
| First event never shown | Event added to a broadcast stream before the builder subscribed | Use `initialData` or add events after the first frame |
| Errors never displayed | `hasError` not checked | Check `hasError` before reading `data` |
| Memory growth after leaving the screen | Controller never closed | Call `close()` in `dispose` |
Choosing between FutureBuilder and StreamBuilder
Use FutureBuilder when the work yields one result, such as a single HTTP request. Use StreamBuilder when values arrive repeatedly, such as sensor readings, a WebSocket, or database change notifications. A request that you retry is still a Future. A new attempt is a new Future assigned in setState, as covered in the retry chapter.
Exercise
A StreamBuilder is given stream: Stream<int>.periodic(const Duration(seconds: 1), (n) => n) directly inside build. The parent widget rebuilds every 200 milliseconds because of an animation. What does the user see, and what is the fix?
Show answer
The user sees the counter stuck at its initial value (the waiting state, or the initialData value if one is given). Each parent rebuild creates a new periodic stream, so StreamBuilder cancels the old subscription and subscribes to the new one before any one-second tick can fire. The fix is to create the stream once, in a State field or in initState, and pass that same object to StreamBuilder on every build.
Exercise
You add events to a StreamController<int>.broadcast() in initState, before the first frame. Your StreamBuilder listens to controller.stream and has no initialData. Is the first event displayed? Why or why not?
Show answer
No. A broadcast stream drops events that arrive while it has no listeners, and the StreamBuilder only subscribes after the widget is built and inserted into the tree. The event is lost. To avoid this, keep the latest value in a field and pass it as initialData, add the event after the first frame (for example from addPostFrameCallback), or use a single-subscription controller, which buffers events until a listener subscribes.