Sub topic 3
Finding widgets with finders
This chapter assumes you can write a basic testWidgets test, know how pumpWidget builds a widget under test, and understand the difference between StatelessWidget and StatefulWidget. Here you learn how to locate widgets in the test tree so you can assert on them or interact with them.
What a finder is
A finder is an object that describes which widgets you want. It is not the widget itself, and it does nothing until you use it. When you pass a finder to expect, to tester.tap, or to tester.widget, Flutter walks the current widget tree and collects the elements that match.
Two consequences follow from this:
- A finder is lazy. You can create it before the widget exists, and it evaluates against the tree at the moment you use it.
- A finder sees the tree as it was at the last
pump. If you change state and do not pump, the finder still sees the old tree.
All the common finders live on the top-level find constant from flutter_test.
final title = find.text('Home');Here title is just a description. No search has happened yet.
The basic finders
The table lists the finders you will use most often.
| Finder | Matches |
|---|---|
| `find.text('Save')` | `Text` widgets whose data equals the string exactly |
| `find.textContaining('Sav')` | `Text` widgets whose data contains the substring |
| `find.byType(AppBar)` | Widgets whose runtime type is exactly `AppBar` |
| `find.byKey(const Key('name'))` | Widgets that have the given key |
| `find.byIcon(Icons.add)` | `Icon` widgets showing that icon data |
| `find.byWidget(widget)` | The specific widget instance you pass in |
| `find.byTooltip('Add')` | Widgets with that tooltip message |
find.text
find.text matches the full string. find.text('Item') does not match Text('Item 1'). It also looks inside RichText and EditableText, so a TextField showing the current value matches by its text too. Use find.textContaining when you only know part of the string.
find.byType
find.byType(ElevatedButton) matches by exact runtime type. A subclass does not match. This matters because several Material buttons are created through factory constructors, such as ElevatedButton.icon, which returns a private subclass. In that case find.byType(ElevatedButton) can miss it. If you need subtypes too, use find.bySubtype<ElevatedButton>().
find.byKey
Keys are the most stable way to target a widget. Text can change with localization, and types are often shared by many widgets. A key identifies one specific widget on purpose. The second code example in the plan uses this approach.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('finds a button by its key', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ElevatedButton(
key: const Key('save'),
onPressed: () {},
child: const Text('Save'),
),
),
),
);
expect(find.byKey(const Key('save')), findsOneWidget);
});
}Use const Key('...') with a string. ValueKey<String>('save') is the same thing, and const Key('save') is a shorthand that creates a ValueKey<String>.
find.byIcon
find.byIcon(Icons.add) matches an Icon widget. It does not match the button that contains the icon. If you tap it, the tap lands at the center of the icon, which is inside the button, so the button receives the gesture. For assertions about the button itself, such as whether it is enabled, find the button with a different finder.
Narrowing a search
Plain text or type often matches too many widgets. Flutter gives you finders that combine conditions.
// Finder variants for locating widgets precisely.
final saveButton = find.widgetWithText(ElevatedButton, 'Save');
final titleInAppBar = find.descendant(
of: find.byType(AppBar),
matching: find.text('Home'),
);
final disabledButtons = find.byWidgetPredicate(
(Widget w) => w is ElevatedButton && w.onPressed == null,
);Each one solves a different problem:
find.widgetWithText(ElevatedButton, 'Save')finds theElevatedButtonthat has aText('Save')somewhere below it. It returns the button, not the text. Matching the button is what you want when you need to readonPressed. Companion finders exist for icons (widgetWithIcon) and for other types.find.descendant(of: ..., matching: ...)finds widgets matchingmatchingthat sit below a widget matched byof. Use it when the same text appears in several places, such as a title in both anAppBarand the body.find.ancestor(of: ..., matching: ...)works in the other direction. It starts from a known widget and looks upward.find.byWidgetPredicateaccepts any function fromWidgettobool. It is the escape hatch for conditions the other finders cannot express, such as a particular property value.
descendant and ancestor accept matchRoot: true if the root widget itself should count as a match. By default it does not.
How finders traverse the tree
By default, finders search the widgets that are in the tree and also ones that are offstage, with one important filter: skipOffstage is true for most finders. That means a widget wrapped in Offstage(offstage: true), or one that sits in an inactive tab of an IndexedStack, is not found unless you opt in.
expect(find.text('Hidden'), findsNothing);
expect(find.text('Hidden', skipOffstage: false), findsOneWidget);This is a common source of confusion. If a widget exists in the code but your finder returns nothing, check whether the widget is hidden, scrolled out of the built range, or on a route that is not on top.
The diagram shows how a finder gets from a description to a result.
Lazy lists and what exists in the tree
Widgets built lazily, such as the items of a ListView.builder, only exist while they are near the viewport. A finder cannot find an item that has not been built.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('scrolls to an item that is not built yet', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: 100,
itemBuilder: (context, i) => ListTile(title: Text('Item $i')),
),
),
),
);
expect(find.text('Item 80'), findsNothing);
await tester.scrollUntilVisible(find.text('Item 80'), 500);
expect(find.text('Item 80'), findsOneWidget);
});
}Here findsNothing does not mean the data is missing. It means the widget has not been built. scrollUntilVisible repeatedly drags the scrollable by 500 logical pixels until the finder matches. Chapter content on scrolling covers this in more detail.
Using finders with first, last and at
A finder can match many widgets. The Finder type exposes helpers that narrow it to one.
final items = find.byType(ListTile);
final firstTile = items.first;
final lastTile = items.last;
final thirdTile = items.at(2);Each of these returns a new finder that matches exactly one widget. Use them when the position is meaningful, such as the first row of a list. Be careful: a test that depends on at(2) breaks when the order changes, so prefer a key when you can.
Reading what a finder found
A finder alone does not give you the widget. To read it, use the finder with tester:
tester.widget<T>(finder)returns the single matching widget as typeT. It throws if there are zero or several matches.tester.widgetList<T>(finder)returns an iterable of all matches.tester.element(finder)returns theElement, which gives you theBuildContext.finder.evaluate()returns the matched elements as an iterable, which is useful for printing or counting.
final greeting = tester.widget<Text>(find.byKey(const Key('greeting')));
expect(greeting.data, 'Hello, Ada');The type argument is a cast. If the widget found is not a Text, the call fails with a type error, so choose a finder that matches the type you ask for.
Common errors
- Zero matches when you expected one. Check for exact text mismatches, trailing spaces, offstage widgets, lazy items, and a missing
pumpafter a state change. - Too many matches.
find.text('Add')may match a title and a button. Narrow withwidgetWithText,descendant, or a key. find.byTypemisses a widget. The widget may be a subclass. TrybySubtype.tester.widgetthrows "Too many elements". The finder matches more than one widget. Usefirst, a narrower finder, orwidgetList.- Stale results. A finder re-evaluates each time you use it, so the finder is fine. The tree is stale if you did not
pump.
Exercise
A screen shows the title "Settings" in both its AppBar and a body heading. find.text('Settings') makes expect(..., findsOneWidget) fail. Write a finder that matches only the AppBar title, and name the finder that lets you select the body heading instead of the first match.
Show answer
Use find.descendant(of: find.byType(AppBar), matching: find.text('Settings')). For the body heading, you can use find.text('Settings').last, or better, give the heading a key and use find.byKey(...), because index-based finders break when the order changes.
Exercise
A ListView.builder has 200 items. Your test calls expect(find.text('Item 150'), findsOneWidget) right after pumpWidget and fails. Why, and what should the test do?
Show answer
Only items near the viewport are built, so Item 150 is not in the tree yet and the finder matches nothing. The test should call await tester.scrollUntilVisible(find.text('Item 150'), 500) first, then assert.