Sub topic 9
Showing something before the first event with initialData
This chapter assumes you can write a StatefulWidget, you know what initState and dispose do, and you have read the earlier chapters on AsyncSnapshot, FutureBuilder, and StreamBuilder. It covers what initialData does, what the snapshot looks like before the first event arrives, and the mistakes that come from misreading that snapshot.
The problem: a snapshot with nothing in it
A StreamBuilder subscribes to its stream when its State is created. Many streams do not emit right away. Stream.periodic waits a full interval before the first event. A stream wrapping a network socket may wait seconds. Until that first event, the builder has nothing to show.
Without initialData, the first snapshot has connectionState == ConnectionState.waiting, data == null, and hasData == false. A builder that reads snapshot.data directly renders the word "null":
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: BadTicker()))));
class BadTicker extends StatefulWidget {
const BadTicker({super.key});
@override
State<BadTicker> createState() => _BadTickerState();
}
class _BadTickerState extends State<BadTicker> {
final Stream<int> _ticks =
Stream<int>.periodic(const Duration(seconds: 1), (n) => n + 1);
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: _ticks,
builder: (context, snapshot) {
// For the first second this prints "Seconds elapsed: null".
return Text('Seconds elapsed: ${snapshot.data}');
},
);
}
}You have two ways to fix this. You can branch on the snapshot and show a placeholder such as a spinner. Or you can supply initialData, so the snapshot already holds a value on the first frame. The second way is the subject of this chapter.
What initialData does
initialData is an optional constructor argument on both StreamBuilder<T> and FutureBuilder<T>. It has type T?. The builder uses it to create the first snapshot, before any real event has arrived.
StreamBuilder<int>(
stream: _ticks,
initialData: 0,
builder: (context, snapshot) {
return Text('Seconds elapsed: ${snapshot.data}');
},
)With initialData: 0, the first frame shows "Seconds elapsed: 0". One second later the first tick arrives and the text changes to 1.
The snapshot differs in a few ways when initialData is set:
| Moment | Without initialData | With initialData: 0 |
|---|---|---|
| First build | `waiting`, `data == null`, `hasData == false` | `waiting`, `data == 0`, `hasData == true` |
| After first event (1) | `active`, `data == 1` | `active`, `data == 1` |
| After the stream closes | `done`, `data == 1` (last value kept) | `done`, `data == 1` |
Two details matter here. First, connectionState is still waiting on the first frame, even though hasData is true. The state describes the connection to the stream. The data describes what you have. They are independent. Second, once a real event arrives, it replaces initialData completely. The builder never merges the two.
The lifecycle of the snapshot
When the builder's State is created, it builds an initial snapshot from initialData and then subscribes to the stream. That moves the state from none to waiting, keeping the data. The none state is only visible to your builder if you pass a null stream, because then nothing subscribes.
The last transition is worth noting. If the stream closes without ever emitting, the snapshot ends in done and still holds initialData. Your UI will keep showing the initial value forever, which is correct but can surprise you if you expected an empty state.
Rendering order: check hasData carefully
initialData changes how you order your checks. Consider the common loading pattern:
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
return Text('${snapshot.data}');
}If you add initialData to this builder, the spinner still shows, because the first frame is waiting. The initialData is never visible. To display it, check hasData first:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: PriceLabel()))));
class PriceLabel extends StatefulWidget {
const PriceLabel({super.key});
@override
State<PriceLabel> createState() => _PriceLabelState();
}
class _PriceLabelState extends State<PriceLabel> {
late final Stream<double> _prices = _priceFeed();
Stream<double> _priceFeed() async* {
await Future<void>.delayed(const Duration(seconds: 2));
yield 101.5;
await Future<void>.delayed(const Duration(seconds: 2));
yield 102.25;
}
@override
Widget build(BuildContext context) {
return StreamBuilder<double>(
stream: _prices,
initialData: 100.0,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Feed error: ${snapshot.error}');
}
final price = snapshot.data!;
final isLive = snapshot.connectionState == ConnectionState.active;
return Text(
'\$${price.toStringAsFixed(2)}${isLive ? '' : ' (last known)'}',
);
},
);
}
}This widget shows "$100.00 (last known)" immediately, switches to "$101.50" after two seconds, and so on. The error check comes first. The snapshot.data! is safe here because initialData is non-null and the error case returned early. When a stream emits an error, the new snapshot has hasError == true and data == null, so initialData and earlier events are dropped from the snapshot.
FutureBuilder also accepts initialData
FutureBuilder takes the same argument. It is useful when you have a cached value and want to show it while a refresh runs:
import 'package:flutter/material.dart';
class CachedProfile extends StatefulWidget {
const CachedProfile({super.key, required this.cachedName});
final String cachedName;
@override
State<CachedProfile> createState() => _CachedProfileState();
}
class _CachedProfileState extends State<CachedProfile> {
late final Future<String> _fresh = _load();
Future<String> _load() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada Lovelace';
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _fresh,
initialData: widget.cachedName,
builder: (context, snapshot) {
final stale = snapshot.connectionState != ConnectionState.done;
return Text(
snapshot.hasError
? 'Could not refresh'
: '${snapshot.data}${stale ? ' (refreshing)' : ''}',
);
},
);
}
}Here initialData comes from widget, which is fine because the argument is read when the builder is created. Notice that the Future is still created once, in a field initializer on State. initialData does not remove the need to keep the Future stable across rebuilds.
When initialData is read, and when it is not
The builder reads initialData once, when its State is created. This has consequences:
- Changing the
initialDataargument on a later rebuild has no effect. The snapshot already exists. - If you swap in a different
streamorfuturelater, the builder unsubscribes from the old one and subscribes to the new one. The snapshot keeps its previous data. It does not reset toinitialData. InconnectionStateterms, it passes throughnoneand thenwaiting, with the old data still attached. - If the builder is removed from the tree and later inserted again, it gets a new
State, andinitialDataapplies again.
This matters when initialData is meant to reflect the current value of something. Consider a controller that holds a counter:
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: _count, // current value, not a hard-coded 0
builder: (context, snapshot) => Text('Count: ${snapshot.data}'),
),
ElevatedButton(
onPressed: () => _controller.add(++_count),
child: const Text('Increment'),
),
],
);
}
}Using _count instead of a literal 0 keeps the display correct if the StreamBuilder is ever rebuilt with a new State, for example when it moves under a different parent. A broadcast stream does not replay past events to new listeners, so a late subscriber would otherwise show 0 until the next increment.
Common mistakes
- Using initialData as a loading placeholder. A value like
-1or an empty string that means "not loaded" ends up on screen if you forget to check for it. If you need a loading state, branch onconnectionStateorhasDataand render a real loading widget. - Passing
nulland expectinghasDatato be true.initialData: nullis the same as noinitialData. For nullable types likeStream<int?>,hasDatais false while the data isnull, so testconnectionStateinstead. - Putting a
connectionState == waitingcheck before ahasDatacheck. As shown above, this hidesinitialDatabehind a spinner. - Expecting initialData to survive an error. The error snapshot has no data.
- Expecting a changed initialData argument to apply. It is read once.
Choosing between initialData and a placeholder
Use initialData when a sensible, truthful starting value exists: a counter at zero, a cached name, the last known price. The UI is then never empty, and you avoid a flash of spinner.
Use an explicit loading state when no truthful value exists, such as a user's profile on first launch. Showing a made-up value there is misleading. In that case, leave initialData out and handle the waiting state in the builder.
Exercise
A StreamBuilder<int> has initialData: 5 and a stream that emits 7 after two seconds and then closes. List the connectionState and data of the snapshot on the first build, after the 7 arrives, and after the stream closes.
Show answer
First build: connectionState is waiting and data is 5, so hasData is true. After the 7 arrives: connectionState is active and data is 7, because the real event replaces initialData. After the stream closes: connectionState is done and data is still 7, because a done snapshot keeps the last value.
Exercise
A builder starts with if (snapshot.connectionState == ConnectionState.waiting) return const CircularProgressIndicator(); and you add initialData: 'cached'. The cached text never appears. Why, and how do you fix it?
Show answer
The first snapshot is always in the waiting state, even when it carries initialData, so the spinner branch runs before the data is read. Check snapshot.hasData first and render the data, or render the data whenever it is non-null and only show the spinner when hasData is false.
Exercise
A stream emits 3, then an error. The builder had initialData: 0. What is snapshot.data when the error is delivered, and how can you still show 3 next to the error message?
Show answer
snapshot.data is null, because an error snapshot carries only the error. To keep showing 3, store each received value in a field on your State (for example from the builder or with a listener on the stream) and read that field when snapshot.hasError is true.