Sub topic 11
Testing FutureBuilder and StreamBuilder Widgets
Assume you know Dart async and await, Flutter widget testing, StatefulWidget, setState, initState, and dispose. This chapter uses flutter_test to control time and verify what asynchronous widgets render.
A widget test builds widgets without opening a real device. You interact with the widget through a WidgetTester, then check the rendered result. Asynchronous tests need explicit time control because a test should not wait for real network or timer delays.
The testing cycle
Most async widget tests follow this sequence:
- Build the widget with
tester.pumpWidget. - Let the first frame render with
tester.pump. - Advance time or deliver stream events.
- Pump again so Flutter processes the changes.
- Verify text, widgets, or callbacks.
pump() runs a frame. pump(const Duration(seconds: 1)) advances the test clock by that duration and then runs a frame. This makes delayed futures predictable.
Testing a FutureBuilder
The following widget displays a loading label, then a name after a delay:
import 'package:flutter/material.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 const Text('Loading');
}
return Text('Hello, ${snapshot.data}');
},
);
}
}A test can use Future.delayed and advance the virtual clock. The test checks both important states:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'name_view.dart';
void main() {
testWidgets('shows loading and then the name', (tester) async {
final future = Future<String>.delayed(
const Duration(seconds: 1),
() => 'Ada',
);
await tester.pumpWidget(
MaterialApp(
home: NameView(future: future),
),
);
expect(find.text('Loading'), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello, Ada'), findsOneWidget);
expect(find.text('Loading'), findsNothing);
});
}The first pumpWidget starts the future but does not advance one second. The first assertion therefore checks the loading state. The second pump completes the delay and lets FutureBuilder rebuild.
To test an error, provide a future that completes with an exception:
testWidgets('shows a future error', (tester) async {
final future = Future<String>.error('Server unavailable');
await tester.pumpWidget(
MaterialApp(
home: NameView(future: future),
),
);
await tester.pump();
expect(find.text('Error: Server unavailable'), findsOneWidget);
});A separate pump() is useful because the error is delivered asynchronously, even though the future is already completed.
Testing a StreamBuilder
A StreamController gives a test direct control over stream events. Close it in a finally block so the test does not leave resources open.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class CountView extends StatelessWidget {
const CountView({super.key, required this.stream});
final Stream<int> stream;
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: stream,
initialData: 0,
builder: (context, snapshot) {
return Text('Count: ${snapshot.data}');
},
);
}
}
void main() {
testWidgets('updates when the stream emits', (tester) async {
final controller = StreamController<int>();
try {
await tester.pumpWidget(
MaterialApp(
home: CountView(stream: controller.stream),
),
);
expect(find.text('Count: 0'), findsOneWidget);
controller.add(3);
await tester.pump();
expect(find.text('Count: 3'), findsOneWidget);
} finally {
await controller.close();
}
});
}controller.add(3) queues an event. pump() processes that event and rebuilds the StreamBuilder. The initialData value makes the first frame deterministic.
| Operation | Purpose |
|---|---|
| `pump()` | Process one frame and pending async work |
| `pump(duration)` | Advance virtual time, then process a frame |
| `pumpAndSettle()` | Pump repeatedly until no scheduled work remains |
Common failures
A test may fail because it checks data before pumping. It may also accidentally use a real network request, making the test slow and unreliable. Pass a fake future or stream into the widget instead.
If a widget creates its future inside build, pumping can start multiple requests. Tests may expose this by seeing repeated loading states or unexpected call counts. Keep the future stable in State, and inject a controllable async value when testing.
Exercise
A StreamBuilder test adds an event to its controller, but the UI still shows the old value. What should the test do next?
Show answer
Call await tester.pump() after controller.add(...) so Flutter processes the event and rebuilds the widget.