Sub topic 11
Testing FutureBuilder and StreamBuilder widgets
What this chapter assumes
You should know how FutureBuilder and StreamBuilder work, what AsyncSnapshot and ConnectionState contain, and why a Future belongs in State rather than in build. You should also have written at least one testWidgets test with flutter_test. This chapter covers how to control time and data so you can check each snapshot state your builder handles.
Why async widgets need controlled tests
An async widget goes through several states: waiting, error, data, and for streams, done. A test must be able to put the widget into each of those states on demand. If the test waits on a real network call or a real timer, it is slow and flaky. It also can't reliably reach the error branch.
Two techniques solve this:
- Give the widget its Future or Stream from outside, through a constructor parameter or a function you can replace. The test then owns the data source.
- Drive the source by hand. Use a
Completerfor a Future and aStreamControllerfor a Stream, and complete or emit when the test says so.
Then you advance the widget tree with tester.pump(), which builds one frame after pending microtasks have run.
How the test clock works
testWidgets runs your test inside a fake-time environment. Timers such as Future.delayed and Stream.periodic don't wait on the wall clock. They fire only when the test advances fake time. The three pump methods differ in how they do that:
| Call | What it does | Typical use |
|---|---|---|
| `await tester.pump()` | Runs pending microtasks, then builds one frame | After completing a Completer or adding a stream event |
| `await tester.pump(duration)` | Advances fake time by `duration`, firing timers due in that span, then builds a frame | After a `Future.delayed` or a periodic stream |
| `await tester.pumpAndSettle()` | Pumps repeatedly until no frames are scheduled | After animations or navigation, once async work is finished |
A related detail: a Future that is already complete, such as Future.value('Ada'), still produces a waiting first frame. FutureBuilder subscribes with then, and that callback runs in a microtask after the first build. Your test must pump once before it sees data. The exception is SynchronousFuture from package:flutter/foundation.dart, which delivers its value on the first frame.
Testing a FutureBuilder with a Completer
The widget under test receives its Future as a parameter. It is a StatelessWidget here because the test, not the widget, owns the Future and keeps it stable.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class NameView extends StatelessWidget {
const NameView({super.key, required this.future});
final Future<String> future;
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: future,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.hasData) {
return Text('Hello, ${snapshot.data}');
}
return const CircularProgressIndicator();
},
);
}
}
Widget wrap(Widget child) {
return MaterialApp(home: Scaffold(body: Center(child: child)));
}
void main() {
testWidgets('shows a spinner, then the data', (tester) async {
final completer = Completer<String>();
await tester.pumpWidget(wrap(NameView(future: completer.future)));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
completer.complete('Ada');
await tester.pump();
expect(find.text('Hello, Ada'), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
});
testWidgets('shows the error when the Future fails', (tester) async {
final completer = Completer<String>();
await tester.pumpWidget(wrap(NameView(future: completer.future)));
completer.completeError(Exception('boom'));
await tester.pump();
expect(find.textContaining('boom'), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
});
}The first test checks the waiting state before the Completer finishes. That check is the one most often skipped, and it is the one that catches a missing loading branch. The second test reaches the error branch without a real failure.
Most test helpers in this chapter call wrap, so keep it in a shared test file.
Testing code that uses real delays
The UserGreeting widget from earlier waits one second inside _fetchName. You can test it without changing the widget, because the delay runs on fake time:
testWidgets('UserGreeting shows the name after one second', (tester) async {
await tester.pumpWidget(wrap(const UserGreeting()));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello, Ada'), findsOneWidget);
});The test takes milliseconds of real time.
Prefer a controllable source when you can, because it separates "what the widget does with each state" from "how the data is produced". A test that depends on a 1-second delay breaks if someone changes the delay to 2 seconds.
Guarding against the recreated Future
The bug from the "Do not create the Future inside build" chapter is easy to test for. Count how many times the loader runs while the parent rebuilds.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class Loader extends StatefulWidget {
const Loader({super.key, required this.load});
final Future<String> Function() load;
@override
State<Loader> createState() => _LoaderState();
}
class _LoaderState extends State<Loader> {
late final Future<String> _future;
@override
void initState() {
super.initState();
_future = widget.load();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _future,
builder: (context, snapshot) => Text(snapshot.data ?? 'Loading...'),
);
}
}
void main() {
testWidgets('does not reload when the parent rebuilds', (tester) async {
var calls = 0;
Future<String> load() async {
calls++;
return 'Ada';
}
await tester.pumpWidget(
MaterialApp(home: Loader(load: load)),
);
await tester.pump();
expect(find.text('Ada'), findsOneWidget);
// Same widget type at the same position: Flutter updates the
// existing State instead of creating a new one.
await tester.pumpWidget(
MaterialApp(home: Loader(load: load)),
);
await tester.pump();
expect(calls, 1);
expect(find.text('Ada'), findsOneWidget);
});
}If someone moves the call into build as future: widget.load(), calls becomes 2 and the test fails. It is a cheap regression test for a bug that is otherwise hard to see.
Testing a StreamBuilder with a StreamController
The approach is the same. The test owns a StreamController, passes its stream to the widget, and adds events by hand.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class TickerView extends StatelessWidget {
const TickerView({super.key, required this.stream});
final Stream<int> stream;
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: stream,
initialData: 0,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text('Seconds elapsed: ${snapshot.data}');
},
);
}
}
void main() {
testWidgets('shows initialData, then each event, then an error',
(tester) async {
final controller = StreamController<int>();
addTearDown(controller.close);
await tester.pumpWidget(
MaterialApp(home: Scaffold(body: TickerView(stream: controller.stream))),
);
expect(find.text('Seconds elapsed: 0'), findsOneWidget);
controller.add(1);
await tester.pump();
expect(find.text('Seconds elapsed: 1'), findsOneWidget);
controller.add(2);
await tester.pump();
expect(find.text('Seconds elapsed: 2'), findsOneWidget);
controller.addError(Exception('lost connection'));
await tester.pump();
expect(find.textContaining('lost connection'), findsOneWidget);
});
}Points to notice:
- The first assertion runs before any event. It proves
initialDatais used on the first frame. - Each
addis followed bypump. Without the pump, the event is queued but the widget has not rebuilt. addTearDown(controller.close)closes the controller even when an assertion fails. This applies the lifecycle rule from the stream chapter to tests.
If you add several events before a single pump, the builder runs once per event, but only one frame is built. You see only the last value. Pump between events when you want to assert each intermediate state.
Testing a stream the widget owns
CounterPanel creates its own broadcast controller, so the test has nothing to inject. Drive it through the UI like a user would:
testWidgets('CounterPanel counts button taps', (tester) async {
await tester.pumpWidget(wrap(const CounterPanel()));
expect(find.text('Count: 0'), findsOneWidget);
await tester.tap(find.text('Increment'));
await tester.pump();
expect(find.text('Count: 1'), findsOneWidget);
await tester.tap(find.text('Increment'));
await tester.pump();
expect(find.text('Count: 2'), findsOneWidget);
});This also shows why the stream is broadcast in that example. The controller starts emitting only after StreamBuilder has subscribed. A broadcast stream drops events nobody is listening to, so events added before the first build would be lost.
Periodic streams and pending timers
Stream.periodic creates a timer. In a widget test, advance fake time with pump(duration):
testWidgets('TickerText counts seconds', (tester) async {
await tester.pumpWidget(wrap(const TickerText()));
expect(find.text('Seconds elapsed: 0'), findsOneWidget);
await tester.pump(const Duration(seconds: 3));
expect(find.text('Seconds elapsed: 3'), findsOneWidget);
// Remove the widget so the stream subscription and its timer are cancelled.
await tester.pumpWidget(const SizedBox());
});The last line matters. Test frameworks check for timers that are still pending at the end of a test, and a periodic stream that is still subscribed keeps one alive. Unmounting the widget cancels the StreamBuilder subscription and the timer with it.
Common mistakes in async widget tests
- Asserting data right after
pumpWidget. The first frame is always the waiting state for an ordinary Future. Pump once more after the Future completes. - Forgetting to pump after
completeoradd. The snapshot changes, but nothing rebuilds until a frame is built. - Using real delays or real network calls. The test becomes slow and non-deterministic. Replace the source with a Completer, a StreamController, or a fake function.
- Letting the widget create the Future in the test's
build. If your test helper builds the Future inside a widget'sbuild, you reproduce the recreation bug in the test. Create the Completer outside the widget tree. - Leaving controllers open. Close them with
addTearDown. - Testing only the happy path. Each branch of the builder (waiting, error, data, and
donefor streams) needs its own test.
What to cover
A reasonable minimum for any screen built on a builder widget:
- The loading state appears on the first frame.
- The data state appears after completion or the first event.
- The error state appears after
completeErrororaddError. - Retry or refresh produces a new loading state, then a new result.
- The loader is called the expected number of times across parent rebuilds.
Exercise
A test creates final completer = Completer<String>();, pumps NameView(future: completer.future), calls completer.complete('Ada'), and then immediately runs expect(find.text('Hello, Ada'), findsOneWidget);. The expectation fails. What is missing, and why?
Show answer
The test must call await tester.pump() after completer.complete('Ada'). Completing the Completer only schedules the FutureBuilder's callback. The callback calls setState, and the widget rebuilds with the data snapshot only when a frame is built. Until then the tree still shows the spinner.
Exercise
Write a test for a StreamBuilder<int> widget that uses initialData: 0. It should check that the widget shows 0 before any event, then shows 5 after the stream emits 5. Which controller type is safe to use, and what should you register so the controller is closed even if the test fails?
Show answer
Create final controller = StreamController<int>(); and call addTearDown(controller.close);. A single-subscription controller is safe because only one StreamBuilder listens. Pump TickerView(stream: controller.stream), expect the text for 0, call controller.add(5), run await tester.pump(), then expect the text for 5. A broadcast controller also works here because the widget subscribes during the first build, before the test adds any event.
Exercise
Why does await tester.pumpAndSettle() time out when called right after pumping a FutureBuilder whose Completer has not been completed, and what should the test do instead?
Show answer
While the Future is pending, the builder shows a CircularProgressIndicator, which animates continuously and keeps scheduling frames. pumpAndSettle waits for frames to stop, so it never settles and times out. The test should assert the loading state directly, then complete the Completer and call await tester.pump(). After the spinner is gone, pumpAndSettle is safe if other animations remain.