Sub topic 5
Tapping and entering text
This chapter covers how a widget test acts like a user. You will tap widgets, type into text fields, and check the results. It assumes you can already build a widget with pumpWidget, locate it with finders, and assert with findsOneWidget and findsNothing. It also assumes you know that pump rebuilds the tree.
What WidgetTester does when you interact
A WidgetTester does not call your onPressed callback directly. It sends pointer events through the same gesture system the real app uses. That makes widget tests more faithful than calling a callback yourself, and it explains most of the errors you will see.
When you call tester.tap(finder), the following happens:
- The tester asks the finder for exactly one element.
- It computes the center of that element's render box in screen coordinates.
- It hit-tests that point against the render tree.
- It dispatches a pointer-down event, then a pointer-up event.
- Gesture recognizers inside the hit widgets decide whether this was a tap and run the handler.
Two consequences follow. The finder must match exactly one widget, and the tap can miss if another widget covers the point or the widget is off screen. Also, setState only marks the widget dirty. The screen does not change until you call pump.
Tapping
tester.tap returns a Future, so always await it. Run it, then pump, then assert.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class SignInForm extends StatefulWidget {
const SignInForm({super.key, required this.onSubmit});
final void Function(String email) onSubmit;
@override
State<SignInForm> createState() => _SignInFormState();
}
class _SignInFormState extends State<SignInForm> {
String _email = '';
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
key: const Key('email'),
onChanged: (value) => setState(() => _email = value),
onSubmitted: widget.onSubmit,
),
ElevatedButton(
key: const Key('submit'),
onPressed: _email.isEmpty ? null : () => widget.onSubmit(_email),
child: const Text('Sign in'),
),
],
);
}
}
void main() {
testWidgets('button is disabled until an email is typed, then submits',
(tester) async {
final submitted = <String>[];
await tester.pumpWidget(
MaterialApp(home: Scaffold(body: SignInForm(onSubmit: submitted.add))),
);
ElevatedButton button() =>
tester.widget<ElevatedButton>(find.byKey(const Key('submit')));
expect(button().onPressed, isNull);
await tester.enterText(find.byKey(const Key('email')), '[email protected]');
await tester.pump();
expect(button().onPressed, isNotNull);
await tester.tap(find.byKey(const Key('submit')));
await tester.pump();
expect(submitted, ['[email protected]']);
});
}The local function button() reads the widget again each time it is called. This matters because the ElevatedButton instance is replaced on each rebuild. A variable captured before pump would hold the old, disabled version.
Other pointer methods
The tester has several related methods. Pick the one that matches the gesture your widget listens for.
| Method | What it does | Typical use |
|---|---|---|
| `tap(finder)` | Taps the center of one widget | Buttons, list tiles, checkboxes |
| `tapAt(offset)` | Taps a screen coordinate | Dismissing a barrier, tapping a spot with no finder |
| `longPress(finder)` | Holds the pointer long enough to trigger a long press | Context menus, selection mode |
| `drag(finder, offset)` | Moves a widget by an offset | Sliders, dismissibles, scrolling |
| `ensureVisible(finder)` | Scrolls ancestors until the widget is on screen | Tapping a widget below the fold |
To tap at a position relative to a widget, combine tapAt with tester.getCenter(finder) or tester.getTopLeft(finder) and add an Offset.
Tapping a disabled control
A disabled ElevatedButton still receives the pointer events. It simply has no handler, so nothing happens and no error is raised. A test that taps a disabled button and then expects a change will fail on the assertion, not on the tap. Check onPressed first, as the example does, when the enabled state is part of the behavior you are testing.
Entering text
tester.enterText(finder, text) simulates the platform keyboard. It does three things: it focuses the field, it sends the text through the text input channel, and it triggers onChanged and any attached TextEditingController update. The finder must resolve to a widget that contains an EditableText, which means TextField, TextFormField and CupertinoTextField all work. Finding a Text widget or a Container around the field does not.
Three behaviors catch people out:
- It replaces the content.
enterTextsets the whole value. Calling it twice with'a'and'b'leaves'b', not'ab'. To test appending, enter the full string. - It does not type character by character.
onChangedruns once with the final string. If your code reacts to every keystroke, such as a debounced search, enter the text in steps. - It needs a pump. Any
setStatetriggered byonChangedtakes effect only afterpump.
To clear a field, enter an empty string:
await tester.enterText(find.byKey(const Key('email')), '');
await tester.pump();Submitting from the keyboard
Users often press the keyboard's action key instead of a button. Simulate that with tester.testTextInput.receiveAction. The field must have focus, which enterText provides.
testWidgets('pressing done on the keyboard submits', (tester) async {
final submitted = <String>[];
await tester.pumpWidget(
MaterialApp(home: Scaffold(body: SignInForm(onSubmit: submitted.add))),
);
await tester.enterText(find.byKey(const Key('email')), '[email protected]');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pump();
expect(submitted, ['[email protected]']);
});To give a field focus without typing, use await tester.showKeyboard(finder). This is useful when you want to assert on focus-dependent UI such as a highlighted border.
Checking what the field holds
There are two reliable ways to read the typed text. If the field has a controller you created in the test, read controller.text. If the widget owns its controller, inspect the widget tree:
final editable = tester.widget<EditableText>(find.byType(EditableText));
expect(editable.controller.text, '[email protected]');find.text('[email protected]') also works, because EditableText renders its content as text. Use findsOneWidget. If the same string appears elsewhere on the screen, the count will be higher, and you should narrow the search with find.descendant.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Bad state: Too many elements` | The finder matched several widgets and `tap` needs one | Use `find.byKey`, `find.widgetWithText`, or `.first` when you really mean the first |
| `Bad state: No element` | The finder matched nothing, often a lazily built list item | Scroll first, or fix the finder |
| Warning that the tap "would not hit test" | The widget is off screen or covered by another widget | Call `ensureVisible`, or change what overlaps it |
| Assertion sees the old UI | You forgot `await tester.pump()` after the interaction | Pump before asserting |
| `enterText` does nothing visible | The finder pointed at a widget that does not contain an `EditableText` | Target the `TextField` itself |
The default test surface is 800 by 600 logical pixels. A widget that would be visible on a phone may be off screen in a test if your layout assumes a different size. When a tap misses for this reason, fix the test setup rather than silencing the warning.
Tapping below the fold
ensureVisible scrolls every scrollable ancestor so the target is on screen. It works only if the target is already built. A SingleChildScrollView builds all its children, so it works. A ListView.builder builds lazily, and for that case you use scrollUntilVisible, which a later chapter covers.
testWidgets('taps a button that starts off screen', (tester) async {
var taps = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
const SizedBox(height: 2000),
ElevatedButton(
key: const Key('bottom'),
onPressed: () => taps++,
child: const Text('Bottom'),
),
],
),
),
),
),
);
await tester.ensureVisible(find.byKey(const Key('bottom')));
await tester.pump();
await tester.tap(find.byKey(const Key('bottom')));
expect(taps, 1);
});The pump after ensureVisible lets the scroll position settle in the rendered tree before the tap computes its coordinates.
A reliable interaction pattern
Most interaction tests follow the same sequence:
- Build the widget with
pumpWidget. - Assert the starting state.
- Perform one interaction with
await. - Call
await tester.pump(), orpumpAndSettle()if an animation is involved. - Assert the new state.
Keep each test to one behavior. When a test taps three things in a row and fails, you have to work out which step broke it. Short tests give a failure message that already points at the cause.
Exercise
A test calls await tester.enterText(find.byType(TextField), 'abc'), then await tester.enterText(find.byType(TextField), 'def'), and expects controller.text to equal 'abcdef'. What does it actually get, and why?
Show answer
It gets 'def'. enterText sets the whole value of the field instead of appending, so the second call replaces the first. To get 'abcdef', enter that complete string in one call.
Exercise
After await tester.tap(find.byKey(const Key('submit'))), an assertion that a success message is visible fails, even though the button's handler ran and called setState. What is missing, and where does it go?
Show answer
The test needs await tester.pump() between the tap and the assertion. setState only marks the widget dirty, and pump runs the frame that rebuilds the tree so the success message exists when expect runs.