Sub topic 6
Rebuilding the tree: pump versus pumpAndSettle
This chapter assumes you can write a basic testWidgets test, build a widget with pumpWidget, and locate widgets with finders. It explains why a test does not see changes until you advance frames, and how to choose between pump, pump with a Duration, and pumpAndSettle.
Why the tree does not rebuild on its own
In a running app, the engine asks Flutter to draw a frame whenever something is dirty. In a widget test there is no engine driving frames. The test binding keeps the widget tree in memory and does nothing until you tell it to run a frame.
When code calls setState, Flutter only marks that element as needing a rebuild. The rebuild happens when the next frame is processed. After tester.tap, the onPressed callback has run, but the tree still shows the old widgets. If you assert right away, you read stale output.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('$_count')),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
void main() {
testWidgets('counter needs a pump after the tap', (tester) async {
await tester.pumpWidget(const MaterialApp(home: Counter()));
await tester.tap(find.byIcon(Icons.add));
// The state changed, but no frame has run yet.
expect(find.text('0'), findsOneWidget);
await tester.pump();
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}Between the tap and the pump, the first expect still sees 0. Most beginners write the second assertion without the pump and wonder why the test fails.
What pump does
await tester.pump() triggers exactly one frame. It rebuilds dirty widgets, lays out, and paints. Fake time does not move forward, because the default duration is zero.
pump takes an optional Duration:
await tester.pump(const Duration(milliseconds: 300));This advances the fake clock by 300 ms, then runs one frame. Animations and timers that were scheduled within that window fire. It is still one frame, not many. An animation that needs 300 ms is therefore sampled once, at the 300 ms mark.
Use pump when you want one precise step. Typical cases are a setState after a tap, and a check of an animation at a known point in time.
What pumpAndSettle does
await tester.pumpAndSettle() calls pump repeatedly until no more frames are scheduled. Its default step is 100 ms of fake time per pump, and its default timeout is 10 minutes of fake time. If frames are still being scheduled when the timeout is reached, it throws.
Use it when you want the UI at rest after something animated: a page transition, a drawer opening, a FutureBuilder that resolves after a delay.
The following test uses it with a fake loader that completes after one second of fake time.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class ProfileName extends StatefulWidget {
const ProfileName({super.key, required this.loadName});
final Future<String> Function() loadName;
@override
State<ProfileName> createState() => _ProfileNameState();
}
class _ProfileNameState extends State<ProfileName> {
late final Future<String> _name = widget.loadName();
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
return Text('Hello, ${snapshot.data}');
},
);
}
}
void main() {
testWidgets('shows a spinner, then the loaded name', (tester) async {
Future<String> fakeLoadName() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: ProfileName(loadName: fakeLoadName)),
),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pumpAndSettle();
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('Hello, Ada'), findsOneWidget);
});
}The one-second delay costs no real time. testWidgets runs the body in a fake-async zone, and pump moves its clock.
The two calls compared
| Call | Frames run | Fake time advanced | Best for |
|---|---|---|---|
| `pump()` | One | None | Applying a `setState` after a tap or text entry |
| `pump(duration)` | One | The given duration | Sampling an animation or firing a timer at a known moment |
| `pumpAndSettle()` | As many as needed | In 100 ms steps until idle | Waiting for transitions and short async work to finish |
How the three calls relate
Edge cases and failure modes
pumpAndSettle times out on endless animations
A CircularProgressIndicator repeats forever. While it is on screen, a frame is always scheduled, so pumpAndSettle never sees an idle tree. It keeps pumping until the timeout and then fails with a message that pumpAndSettle timed out.
This applies to any widget with a repeating animation: indeterminate progress indicators, a blinking text cursor in a focused TextField (in many versions the cursor blink is handled so it does not block, but custom repeating animations do), and AnimationController.repeat().
The fix is to step by hand while the indicator is visible:
await tester.pump(const Duration(seconds: 1));
expect(find.text('Hello, Ada'), findsOneWidget);In the ProfileName test above, pumpAndSettle works because the spinner disappears once the future completes. Before that point, the spinner would block settling only if nothing else ended the animation. Here the first pump after the one-second delay replaces it, and the tree then goes idle.
pump with a Duration is one frame, not a loop
A common mistake is await tester.pump(const Duration(seconds: 2)) and expecting a two-second animation to have run in 16 ms steps. The clock jumps two seconds, and one frame is drawn at the end. For most assertions on the final state this is fine. For intermediate states, such as checking opacity at 50%, pump to that time directly:
await tester.pump(const Duration(milliseconds: 150)); // half of a 300 ms animationTimers that are still pending at the end of the test
If a Timer or a delayed Future is still pending when the test body returns, the framework fails the test with A Timer is still pending even after the widget tree was disposed. Advance time past the timer, or cancel it in dispose, so that the test ends cleanly.
Async work that is not driven by fake time
pump advances the fake clock, so Future.delayed and Timer complete. Real I/O does not. File reads, real network calls, and platform channels without a mock use real time and never finish under the fake clock. Replace them with fakes (a later chapter covers this). tester.runAsync exists for the rare case where real async work is unavoidable, but it makes tests slower and less predictable.
pumpWidget is also a pump
pumpWidget builds the tree and then runs a frame, so you do not need a separate pump right after it. Calling pumpWidget a second time with a different widget replaces the tree. If the new root is the same type, Flutter updates the existing elements and keeps state, which is a handy way to test didUpdateWidget.
Choosing in practice
- After a plain state change (
tap,enterText), usepump(). - To check an animation or a timer at a given point, use
pump(duration). - To wait for a navigation transition, a dialog, or a short async load, use
pumpAndSettle(). - If
pumpAndSettletimes out, look for a repeating animation and switch topump(duration). - Do not add
pumpAndSettleeverywhere as a habit. It hides timing assumptions, can mask bugs where something never settles, and makes failures harder to read.
A worked example with a timed animation
This test checks a widget at three points in time: before the animation, halfway through, and after it ends. It uses AnimatedOpacity and reads the animated value through the widget.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class FadeBox extends StatefulWidget {
const FadeBox({super.key});
@override
State<FadeBox> createState() => _FadeBoxState();
}
class _FadeBoxState extends State<FadeBox> {
double _opacity = 1.0;
@override
Widget build(BuildContext context) {
return Column(
children: [
AnimatedOpacity(
opacity: _opacity,
duration: const Duration(milliseconds: 400),
child: const Text('Fading text', key: Key('fade')),
),
ElevatedButton(
onPressed: () => setState(() => _opacity = 0.0),
child: const Text('Hide'),
),
],
);
}
}
void main() {
testWidgets('opacity animates over 400 ms', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: FadeBox())),
);
double currentOpacity() {
final render = tester.renderObject<RenderAnimatedOpacity>(
find.byType(AnimatedOpacity),
);
return render.opacity.value;
}
expect(currentOpacity(), 1.0);
await tester.tap(find.text('Hide'));
await tester.pump(); // starts the animation
await tester.pump(const Duration(milliseconds: 200));
expect(currentOpacity(), closeTo(0.5, 0.1));
await tester.pumpAndSettle();
expect(currentOpacity(), 0.0);
});
}The first pump() after the tap is needed to rebuild with the new target opacity. That frame starts the animation clock. The second pump moves 200 ms into it. pumpAndSettle then finishes the remaining time.
Exercise
A test taps a button that opens a screen containing an indeterminate CircularProgressIndicator that spins until a request ends. The request is a fake that never completes. Why does await tester.pumpAndSettle() throw, and what call would you use instead to check that the spinner is shown?
Show answer
The spinner schedules a new frame on every tick, so the tree never becomes idle and pumpAndSettle hits its timeout and throws. Use await tester.pump() (or pump(const Duration(milliseconds: 500))) to show the new screen, then assert with expect(find.byType(CircularProgressIndicator), findsOneWidget).
Exercise
After await tester.tap(find.byIcon(Icons.add)), an assertion expect(find.text('1'), findsOneWidget) fails, although the app works when you run it by hand. What is the most likely cause, and how do you fix it?
Show answer
The setState in the button callback only marked the widget dirty, and no frame has run in the test. Add await tester.pump(); between the tap and the expect.