Sub topic 8
Rendering a Stream with StreamBuilder
Assume you know Dart async and await, Flutter widgets, StatefulWidget, setState, initState, and dispose. This chapter focuses on streams: values that arrive over time and cause the UI to update.
One value versus many values
A Future<T> completes once with a value or an error. A Stream<T> can produce zero, one, or many values. A stream can also report an error and later finish.
Examples of streams include:
- A timer that emits once per second.
- A WebSocket that receives messages.
- A database query that reports changed records.
- A
StreamControllerthat receives events from your application.
StreamBuilder<T> subscribes to a stream and rebuilds its child whenever the stream sends an event. Its builder receives an AsyncSnapshot<T>, which describes the latest known state.
Read the snapshot before rendering
The most useful AsyncSnapshot properties are:
| Property | Meaning |
|---|---|
| `connectionState` | Whether the stream is waiting, active, done, or disconnected |
| `hasData` | Whether a data value is available |
| `data` | The latest stream value |
| `hasError` | Whether the latest state contains an error |
| `error` | The error object |
For a normal stream, ConnectionState.active means the subscription is connected and can receive events. ConnectionState.done means the stream has closed. A stream may be active even when its latest snapshot has no data, so check the state you need rather than assuming that every active snapshot contains a value.
Build a live-updating widget
This example displays the number of seconds since the stream started:
import 'package:flutter/material.dart';
class TickerText extends StatefulWidget {
const TickerText({super.key});
@override
State<TickerText> createState() => _TickerTextState();
}
class _TickerTextState extends State<TickerText> {
late final Stream<int> _ticks;
@override
void initState() {
super.initState();
_ticks = Stream<int>.periodic(
const Duration(seconds: 1),
(count) => count + 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}');
},
);
}
}initialData: 0 gives the builder a value for the first build, before the first timer event arrives. Without it, snapshot.data can be null initially.
StreamBuilder manages the subscription. When the widget is removed, it cancels the subscription. When the stream property changes, it unsubscribes from the old stream and subscribes to the new one.
Keep the stream identity stable
Create the stream in initState or store it in a field when the state is created. Do not create a new stream directly inside build:
// Avoid this pattern.
StreamBuilder<int>(
stream: Stream<int>.periodic(const Duration(seconds: 1)),
builder: (context, snapshot) {
return Text('${snapshot.data}');
},
)build can run many times. Creating a new stream there can restart the stream and create repeated subscriptions. It can also reset the snapshot unexpectedly. If the stream depends on a changing value, create a new stream deliberately when that value changes, such as in response to setState, and let StreamBuilder switch subscriptions.
Controllers and stream ownership
A StreamController<T> lets your code add events manually:
final controller = StreamController<int>.broadcast();
controller.add(1);
controller.add(2);
controller.addError(Exception('Failed'));
await controller.close();A single-subscription stream allows only one listener. Use it for one consumer, such as a one-time operation. A broadcast stream allows multiple listeners. Use broadcast only when multiple listeners are part of the design.
If a State object owns a controller, close it in dispose:
@override
void dispose() {
_controller.close();
super.dispose();
}Closing prevents future events and releases resources owned by the controller. Do not close a controller owned by another service or provider.
Exercise
Why should a periodic stream usually be stored in a State field instead of created inside build?
Show answer
Because build can run repeatedly. Storing the stream keeps its subscription and progress stable instead of restarting it during every rebuild.