Sub topic 5
Finding widgets and simulating user input
This chapter covers how an integration test locates widgets on screen and acts on them. It assumes you have a working integration_test setup and a first test that launches the app with app.main(). It also assumes you know what a Key is and have used find and expect in a widget test. The next chapter covers frame pumping in more depth. Here, pumpAndSettle appears only where each interaction needs it.
How a test step is built
Almost every step in an integration test has the same shape. A finder locates a widget, the WidgetTester acts on it, the test pumps frames so the app can react, and an expect checks the result.
A finder only describes a widget. It does not search until something uses it. tester.tap(finder) and expect(finder, matcher) both evaluate the finder against the widget tree as it is at that moment. If you hold a finder in a variable and the tree changes, the same finder returns new results the next time you use it.
Finders
All finders live on the find constant from flutter_test. The ones you will use most are in this table.
| Finder | Matches | Typical use |
|---|---|---|
| `find.byKey(const Key('increment'))` | The widget with that key | Buttons, fields, anything you control |
| `find.text('Welcome')` | `Text` widgets (and editable text) whose string equals the argument | Checking visible content |
| `find.textContaining('Welc')` | Text that contains the substring | Messages with dynamic parts |
| `find.byType(ListView)` | Widgets of an exact runtime type | Scrollables, one-of-a-kind widgets |
| `find.byIcon(Icons.add)` | `Icon` widgets showing that icon | Icon-only buttons |
| `find.byTooltip('Increment')` | Widgets with that tooltip message | Icon buttons that set a tooltip |
| `find.widgetWithText(ElevatedButton, 'Sign in')` | A widget of a type that has a given text descendant | Labelled buttons |
| `find.descendant(of: a, matching: b)` | Widgets matching `b` inside the subtree of `a` | Disambiguating repeated widgets |
| `find.bySemanticsLabel('Email')` | Widgets whose semantics label matches | Apps with good accessibility labels |
Why keys come first
A text finder breaks when copy changes or the app is localized. A type finder breaks when two widgets of the same type are on screen. A key is stable and unique, and it is invisible to users. Add keys to the widgets your tests touch.
This is the screen the login test in this chapter runs against. It must sit under a MaterialApp that main() starts.
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _email = TextEditingController();
bool _signedIn = false;
@override
void dispose() {
_email.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_signedIn) {
return const Scaffold(body: Center(child: Text('Welcome')));
}
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
key: const Key('email_field'),
controller: _email,
decoration: const InputDecoration(labelText: 'Email'),
),
ElevatedButton(
key: const Key('submit_button'),
onPressed: () => setState(() => _signedIn = true),
child: const Text('Sign in'),
),
],
),
),
);
}
}Keys on the field and the button let the test find them without depending on the label text.
Matchers for finders
expect takes a finder and a matcher that states how many widgets should match.
findsOneWidget: exactly one match.findsNothing: zero matches.findsNWidgets(3): exactly three matches.findsWidgets: one or more.findsAtLeastNWidgets(2): two or more.
A key should match exactly one widget. If findsOneWidget fails on a keyed finder, you probably reused the same key in two places, such as list rows built with the same literal key.
Simulating input
The WidgetTester methods below send input into the running app.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('login form accepts input', (tester) async {
app.main();
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('email_field')), '[email protected]');
await tester.tap(find.byKey(const Key('submit_button')));
await tester.pumpAndSettle();
expect(find.text('Welcome'), findsOneWidget);
});
}The test takes four actions:
- It starts the real app.
- It types into the email field.
- It taps the button.
- It waits for the screen change before asserting.
What tap and enterText actually do
On a real device it is easy to assume the test is touching the glass. It is not. tester.tap computes the center of the widget, then injects pointer-down and pointer-up events into Flutter's gesture system. The operating system never sees them. For the same reason, tester.enterText does not press keys on the on-screen keyboard. It gives the field focus and replaces its whole text value, as if the keyboard had produced it.
This has three consequences:
- Tests run quickly and do not depend on the keyboard layout or the language of the device.
- A test cannot interact with anything outside Flutter's rendering, such as a native permission dialog, a system share sheet, or a platform view's inner content. Handle those with a different tool or configure the device in advance.
- Keyboard-specific behavior, such as autocorrect, is not exercised.
Other interactions
| Method | Effect |
|---|---|
| `tester.tap(finder)` | Tap the center of the widget |
| `tester.longPress(finder)` | Press and hold |
| `tester.doubleTap(finder)` | Two quick taps |
| `tester.drag(finder, const Offset(0, -200))` | Drag by an offset |
| `tester.fling(finder, offset, speed)` | Drag and release with velocity |
| `tester.ensureVisible(finder)` | Scroll ancestors until the widget is on screen |
| `tester.scrollUntilVisible(finder, delta)` | Scroll repeatedly until the widget is found |
| `tester.testTextInput.receiveAction(TextInputAction.done)` | Simulate pressing the keyboard action key |
If a form submits from the keyboard's action key, use receiveAction after enterText. Tapping a button is not equivalent in that case.
await tester.enterText(find.byKey(const Key('email_field')), '[email protected]');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pumpAndSettle();Scrolling to widgets that are not built yet
Lazy lists such as ListView.builder only build the rows near the viewport. A finder for row 49 returns nothing until you scroll there. Phones have small screens, so this comes up more often than in widget tests, where the default test surface is larger.
scrollUntilVisible scrolls in steps of delta pixels, looking for the finder after each step. Pass the scrollable explicitly so it is clear which list you mean.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('opens a row far down the list', (tester) async {
app.main();
await tester.pumpAndSettle();
final target = find.byKey(const Key('item_49'));
await tester.scrollUntilVisible(
target,
300,
scrollable: find.byType(Scrollable).first,
);
await tester.tap(target);
await tester.pumpAndSettle();
expect(find.text('Details for item 49'), findsOneWidget);
});
}This test assumes the list's rows carry keys such as Key('item_$index') and that a tap opens a details page showing that text. The positive delta scrolls toward later items. If the target is above you, pass a negative value.
ensureVisible is the right tool when the widget already exists in the tree but is off screen, for example a button at the bottom of a long SingleChildScrollView form.
Reading state back from widgets
Sometimes find.text is not enough, for instance when you need to know a field's current value or a button's enabled state. Fetch the widget from the finder and read its properties.
final field = tester.widget<TextField>(find.byKey(const Key('email_field')));
expect(field.controller?.text, '[email protected]');
final button = tester.widget<ElevatedButton>(find.byKey(const Key('submit_button')));
expect(button.onPressed, isNotNull);tester.widget throws if the finder matches zero or several widgets, so it also works as a check that your finder is unique. Prefer asserting on what the user sees, and use property checks only where nothing visible exists to assert on.
Common errors
Too many elements or Bad state
tester.tap and tester.widget require exactly one match. A message such as "Too many elements" means the finder is ambiguous. Typical causes and fixes:
find.text('0')also matches a text that merely contains the same string elsewhere on screen. Scope it withfind.descendantor use a key.find.byType(ElevatedButton)matches every button. Usefind.widgetWithTextor a key.- During a page transition, both the old and new pages are in the tree. Pump until the transition ends before searching.
.firstsilences the error but hides the ambiguity. Use it only when any match is acceptable.
Zero matches
A "No element" error means nothing matched at that moment. Check, in order:
- Did you pump after the previous action? The new screen may not be built yet.
- Is the widget in a lazy list that has not scrolled it into view?
- Does the string or key differ in some small way, such as a trailing space or a different key type?
- Is the app still on a loading or splash screen?
The tap hits nothing
The tester warns "A call to tap() with finder ... derived an Offset ... that would not hit test on the specified widget". The widget exists but its center is off screen, covered by another widget such as a bottom sheet, or inside an IgnorePointer. Call ensureVisible first, or close whatever covers it. Treat this warning as a failure even though the test may continue, since the tap did not reach the widget.
Text entered, nothing happens
enterText changes the text but does not submit it. If the app reacts on submit, either tap the button or call receiveAction. If the app reacts through onChanged, enterText triggers it.
Exercises
Exercise
A test calls await tester.tap(find.byType(ElevatedButton)); and fails with "Too many elements". Give two ways to fix it without adding .first.
Show answer
Give the intended button a key and use find.byKey(const Key('submit_button')). Alternatively, narrow the finder by its label with find.widgetWithText(ElevatedButton, 'Sign in'), or scope it with find.descendant(of: find.byKey(const Key('login_form')), matching: find.byType(ElevatedButton)). Each option makes the finder match exactly one widget.
Exercise
Your test enters text into a search field with tester.enterText(...), but the app only starts searching when the keyboard's search action is pressed, and the results never appear. What do you add, and why does enterText alone not trigger the search?
Show answer
Add await tester.testTextInput.receiveAction(TextInputAction.search); followed by await tester.pumpAndSettle();. enterText only sets the field's text and focus. It does not send the keyboard action that the field's onSubmitted handler listens for, because the test never uses the real on-screen keyboard.
Exercise
A list shows 100 rows built lazily with ListView.builder. find.byKey(const Key('item_80')) finds nothing even though the app is on the right screen. Write the call that fixes it before tapping the row.
Show answer
await tester.scrollUntilVisible(find.byKey(const Key('item_80')), 300, scrollable: find.byType(Scrollable).first); Row 80 is not built until it scrolls near the viewport, so the finder matches nothing until then. After this call, tester.tap on the same finder works.