Sub topic 10
Tapping, entering text and pumping frames
This chapter assumes you can write a basic testWidgets test, use finders such as find.text and find.byType, and read async/await code. Here you will learn to drive a widget with WidgetTester and to control when frames are drawn.
Why a test must drive time itself
A widget test does not run a real app loop. The framework builds the widget once, and after that it draws a new frame only when you ask for one. Timers and animations run on a fake clock that moves only when you advance it.
This explains the most common beginner bug. You tap a button, the code calls setState, and your expect still sees the old screen. The state changed, but no frame was built. The tester methods below simulate user input, and the pump methods draw frames.
Simulating input
WidgetTester can send the same kinds of input a user would. Each of these methods takes a finder, which says where the input lands.
| Method | What it does |
|---|---|
| `tap(finder)` | Taps the center of the widget. |
| `longPress(finder)` | Presses and holds. |
| `enterText(finder, text)` | Replaces the text of a `TextField` or `TextFormField` with `text`. |
| `drag(finder, offset)` | Moves a pointer by `offset` over the widget. |
| `fling(finder, offset, speed)` | Drags quickly and releases, so scrolling continues. |
| `ensureVisible(finder)` | Scrolls ancestors until the widget is on screen. |
| `scrollUntilVisible(finder, delta)` | Scrolls repeatedly by `delta` until the widget is built and visible. |
All of these return futures, so you await them. None of them draws the result on screen. For that you pump.
The pump methods
There are three ways to move a widget test forward.
| Call | Behavior |
|---|---|
| `pump()` | Draws exactly one frame. The fake clock does not advance. |
| `pump(Duration d)` | Advances the fake clock by `d`, fires any timers that come due, then draws one frame. |
| `pumpAndSettle()` | Calls `pump` repeatedly, in 100 ms steps by default, until no frame is scheduled. |
pumpWidget is also a pump. It mounts the widget and draws the first frame.
A worked example
The page below has a text field and a button. When you tap the button it shows a spinner, waits one second, then shows a greeting.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class GreetingPage extends StatefulWidget {
const GreetingPage({super.key});
@override
State<GreetingPage> createState() => _GreetingPageState();
}
class _GreetingPageState extends State<GreetingPage> {
final _controller = TextEditingController();
String? _greeting;
bool _loading = false;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _greet() async {
setState(() => _loading = true);
await Future<void>.delayed(const Duration(seconds: 1));
if (!mounted) return;
setState(() {
_loading = false;
_greeting = 'Hello, ${_controller.text}!';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
key: const Key('nameField'),
controller: _controller,
decoration: const InputDecoration(labelText: 'Name'),
),
ElevatedButton(
onPressed: _loading ? null : _greet,
child: const Text('Greet'),
),
if (_loading) const CircularProgressIndicator(),
if (_greeting != null) Text(_greeting!),
],
),
),
);
}
}
void main() {
testWidgets('shows a spinner, then the greeting', (tester) async {
await tester.pumpWidget(const MaterialApp(home: GreetingPage()));
await tester.enterText(find.byKey(const Key('nameField')), 'Ada');
await tester.tap(find.text('Greet'));
await tester.pump();
expect(find.byType(CircularProgressIndicator), findsOneWidget);
expect(find.text('Hello, Ada!'), findsNothing);
await tester.pump(const Duration(seconds: 1));
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('Hello, Ada!'), findsOneWidget);
});
}Follow the test step by step:
enterTextputsAdainto the field. The controller now holds the text, and the framework schedules a frame.taptriggers_greet. The firstsetStatemarks the page dirty andFuture.delayedregisters a timer on the fake clock.pump()draws one frame, so the spinner appears. The clock has not moved, so the greeting does not exist yet.pump(const Duration(seconds: 1))advances the clock. The timer fires, the secondsetStateruns, and the frame that follows shows the greeting.
Checking the loading state before advancing the clock is a useful habit. It proves the intermediate screen exists, not only the final one.
Using pumpAndSettle
You can replace the last two steps with a single call.
await tester.tap(find.text('Greet'));
await tester.pumpAndSettle();
expect(find.text('Hello, Ada!'), findsOneWidget);This works because pumpAndSettle keeps stepping the clock in 100 ms increments. After ten steps the timer fires, the spinner is removed, and no frame remains scheduled, so the call returns.
The cost is that you no longer see the in-between states. Choose pump(Duration) when the delay is part of the behavior you are testing. Choose pumpAndSettle when you only care about the end state, such as after a page transition or a ripple.
Entering text correctly
enterText changes the field's value directly. It does not type character by character, so it does not trigger key events. That is usually what you want, but keep these points in mind:
- The finder must match exactly one widget.
find.byType(TextField)fails when the screen has two fields, so give each field aKeyor usefind.widgetWithText. - The finder can match the
TextFieldor theTextFormField. Both work. - A
TextFieldwithonChangedcalls it once for the whole replaced text. - To simulate pressing the keyboard action, call
await tester.testTextInput.receiveAction(TextInputAction.done);and then pump. This triggersonSubmitted.
You can check the entered text through the controller. You can also check it with find.text('Ada'), because EditableText renders the current value.
Scrolling to widgets that are not built
ListView.builder builds only the rows near the visible area. A row far down the list does not exist in the tree, so find.text returns nothing for it, and calling tap on that finder fails. Scroll first.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('scrolls to an item far down the list', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: 50,
itemBuilder: (context, index) =>
ListTile(title: Text('Item $index')),
),
),
),
);
expect(find.text('Item 40'), findsNothing);
await tester.scrollUntilVisible(
find.text('Item 40'),
200,
scrollable: find.byType(Scrollable),
);
expect(find.text('Item 40'), findsOneWidget);
});
}scrollUntilVisible drags by delta pixels and pumps after each drag, up to maxScrolls times (50 by default). A positive delta scrolls toward the end of the list. If the item never appears, the call fails instead of looping forever.
You can also scroll by hand with await tester.drag(find.byType(ListView), const Offset(0, -300)); followed by await tester.pump();. A drag with a negative dy moves the content up, which reveals later rows.
Common errors
The tap hits nothing
Flutter may print a warning that tap() derived an offset that would not hit test on the widget. The widget is probably covered by another widget, such as a dialog or an overlay. It may also sit outside the test screen, which is 800 by 600 logical pixels by default. Call ensureVisible or scroll first. Pass warnIfMissed: false only when you are deliberately testing a tap that should miss.
The tap does nothing
A button with onPressed: null is disabled. In the example, the button is disabled while _loading is true, so a second tap before the delay ends has no effect. This is a feature to test, not a bug.
The expectation runs too early
If an expect fails with "Found 0 widgets" right after an interaction, add the missing pump. If it works with pumpAndSettle but not with pump(), the result depends on time or on a multi-frame animation.
Pending timers at the end of the test
If code under test starts a Timer that is still pending when the test ends, the framework reports "A Timer is still pending even after the widget tree was disposed." Either pump long enough for the timer to fire, or cancel it in dispose, which is the better fix.
Real async work hangs
Plain await on real I/O inside a widget test can stall, because the test body runs under the fake clock. Replace network and disk calls with fakes, as covered in the chapters on test doubles, so every delay in your test is one you control.
Exercise
A test taps a "Save" button. The handler calls setState immediately, then awaits Future.delayed(Duration(seconds: 2)), then calls setState again to show "Saved". Which calls would you make after the tap to assert both the "Saving..." state and the "Saved" state?
Show answer
Call await tester.pump(); to draw the frame after the first setState, and assert that "Saving..." is shown. Then call await tester.pump(const Duration(seconds: 2)); to fire the timer and draw the second state, and assert that "Saved" is shown. A single pumpAndSettle() would skip the "Saving..." state, because it would run until the end.
Exercise
Your test calls await tester.pumpAndSettle(); on a screen that shows a CircularProgressIndicator for as long as a request is pending, and the request is never completed. What happens, and how do you fix the test?
Show answer
The indicator schedules a frame on every tick, so the app never settles. pumpAndSettle fails with a timeout after 10 minutes of fake time. Replace it with await tester.pump(const Duration(milliseconds: 100)); (or another fixed duration), then assert that the indicator is present. To test the finished state, complete the fake request first.
Exercise
find.text('Item 40') returns nothing in a ListView.builder test, although the list has 50 items. What is the cause, and which call fixes it?
Show answer
The builder creates only the rows near the visible area, so row 40 is not in the widget tree. Call await tester.scrollUntilVisible(find.text('Item 40'), 200); (or drag the list and pump) before you look for the item.