Sub topic 9
Showing Something Before the First Event with `initialData`
Why the first frame matters
This chapter assumes you know Dart async and await, Flutter widgets, StatefulWidget, build, and StreamBuilder.
A StreamBuilder rebuilds a widget when its stream emits a value. However, a stream may need time to produce its first event. During that time, the builder receives an AsyncSnapshot whose connectionState is usually ConnectionState.waiting.
If the UI reads snapshot.data immediately, the value may be null. You could show a spinner, but sometimes a better choice is to show a useful starting value. The initialData property supplies that value for the first snapshot.
initialData is not sent through the stream. It is only the value that the builder can display before the first stream event arrives.
import 'dart:async';
import 'package:flutter/material.dart';
class TemperaturePanel extends StatefulWidget {
const TemperaturePanel({super.key});
@override
State<TemperaturePanel> createState() => _TemperaturePanelState();
}
class _TemperaturePanelState extends State<TemperaturePanel> {
late final Stream<double> _temperatures;
@override
void initState() {
super.initState();
_temperatures = Stream<double>.periodic(
const Duration(seconds: 2),
(count) => 20 + count.toDouble(),
);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<double>(
stream: _temperatures,
initialData: 20,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text(
'Temperature: ${snapshot.data?.toStringAsFixed(1)}°C',
);
},
);
}
}The first build displays 20°C, even though the periodic stream has not emitted its first event. After two seconds, the stream emits 20.0, and the builder runs again. Later events update the displayed value.
How `initialData` affects `AsyncSnapshot`
An AsyncSnapshot<T> describes the latest state of an asynchronous source. For a StreamBuilder, the important fields are:
connectionStatetells you whether the stream is waiting, active, done, or disconnected.datacontains the initial value or the latest event.errorcontains an error if the stream reports one.hasDatatells you whether the snapshot contains non-null data.hasErrortells you whether an error was reported.
A stream with initialData can begin with ConnectionState.waiting and still have usable data. Do not treat waiting as proof that snapshot.data is null.
Choose a safe starting value
The initial value should be meaningful and safe to display. For example, 0 may be correct for a counter, but it may be misleading for a bank balance if the real balance has not loaded yet.
For values where no default is honest, use a nullable type and show a loading label instead:
StreamBuilder<String?>(
stream: userNameStream,
initialData: null,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Could not load the name: ${snapshot.error}');
}
final name = snapshot.data;
return Text(name == null ? 'Loading name...' : 'Hello, $name');
},
)The builder must also handle errors. initialData does not prevent a later stream error, and it does not replace error handling.
> callout note > Use initialData when a temporary value is useful and accurate enough. Do not use a fake value that users could mistake for confirmed data.
FutureBuilder also has an initialData property. It can display a previous or placeholder value while a future completes. The same rule applies: the value is available to the builder before completion, but it does not change the future's result.
Common mistakes
- Assuming
initialDatais emitted by the stream. - Showing a default value that looks like confirmed server data.
- Checking only
connectionStateand ignoring an available initial value. - Forgetting to handle
snapshot.hasError. - Creating the stream inside
build, which can restart the subscription during rebuilds.
Keep the stream stable by creating it in initState, storing it in a field, or obtaining it from a stable state-management object.
Exercise
A StreamBuilder<int> has initialData: 5, and its stream has not emitted yet. What should the builder expect in snapshot.data, and what is the likely connection state?
Show answer
snapshot.data is 5, and the likely connection state is ConnectionState.waiting.