Sub topic 9
Finding widgets and asserting on them
A widget test builds a widget tree and then asks questions about it. Those questions have two parts. A finder locates widgets in the tree. A matcher checks what the finder returned. This chapter covers both, plus the errors you will hit most often.
I assume you can write a basic testWidgets test that calls tester.pumpWidget, and that you know what a Key is. Tapping and entering text come in the next chapter, so the tests here only build a widget and inspect it.
The model: a finder is a lazy query
A Finder does not hold widgets. It holds a description of what to look for. The search runs against the current widget tree each time a matcher or a WidgetTester method evaluates the finder.
This has two consequences:
- You can create a finder before the widget exists and reuse it after later frames.
- A value you extract from a finder, such as the result of
tester.widget, is a snapshot. After the tree changes, fetch it again.
A widget to test
The examples below use this widget. Save it, with the tests that follow, in one file such as test/todo_list_test.dart.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class TodoList extends StatelessWidget {
const TodoList({super.key, required this.items});
final List<String> items;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: items.isEmpty
? const Center(child: Text('Nothing to do'))
: ListView(
children: [
for (final item in items)
ListTile(
leading: const Icon(Icons.check_box_outline_blank),
title: Text(item),
),
],
),
floatingActionButton: FloatingActionButton(
key: const Key('add_button'),
onPressed: () {},
tooltip: 'Add todo',
child: const Icon(Icons.add),
),
);
}
}
Widget wrap(Widget child) => MaterialApp(home: child);
void main() {
testWidgets('shows the title and one row per item', (tester) async {
await tester.pumpWidget(wrap(const TodoList(items: ['Milk', 'Eggs'])));
expect(find.text('Todos'), findsOneWidget);
expect(find.byType(ListTile), findsNWidgets(2));
expect(find.text('Milk'), findsOneWidget);
expect(find.text('Bread'), findsNothing);
});
}The wrap helper puts the widget under a MaterialApp. Widgets such as Scaffold and Text need the inherited data that MaterialApp provides, such as a Directionality and a theme.
The built-in finders
The find object offers many constructors. These are the ones you will use most.
| Finder | Matches | Caveat |
|---|---|---|
| `find.text('Milk')` | `Text` widgets whose whole string equals `'Milk'` | Exact match. Use `find.textContaining('Mi')` for a partial match. |
| `find.byType(ListTile)` | Widgets whose runtime type is exactly `ListTile` | Does not match subclasses. Use `find.bySubtype<T>()` for those. |
| `find.byKey(const Key('add_button'))` | The widget with that key | Most stable choice when the text or layout may change. |
| `find.byIcon(Icons.add)` | `Icon` widgets showing that icon data | Several icons of the same kind give several matches. |
| `find.byTooltip('Add todo')` | Widgets with that tooltip message | Useful for icon-only buttons. |
| `find.widgetWithText(ListTile, 'Milk')` | A `ListTile` that has `'Milk'` as a descendant | Returns the ancestor, not the text. |
| `find.byWidgetPredicate(fn)` | Any widget for which `fn` returns true | Flexible but harder to read. |
Choosing a finder
Prefer the finder that describes what a user would notice, as long as it is stable. Text and icons are good when they are part of the contract. Keys are better when the text is translated or likely to change. Type finders work well for counting repeated elements.
Narrowing a search
When one finder matches too much, combine finders by relationship. find.descendant searches inside another finder's matches. find.ancestor searches upward.
testWidgets('finds text inside a specific row', (tester) async {
await tester.pumpWidget(wrap(const TodoList(items: ['Milk', 'Eggs'])));
final row = find.widgetWithText(ListTile, 'Milk');
expect(row, findsOneWidget);
expect(
find.descendant(of: row, matching: find.byType(Icon)),
findsOneWidget,
);
expect(
find.byWidgetPredicate((w) => w is Text && w.data == 'Eggs'),
findsOneWidget,
);
});When you do have several matches and you want one, use .first, .last or .at(n) on the finder. Use this sparingly. An index depends on build order, so a harmless layout change can break the test.
Matchers for finders
You pass a finder and a matcher to expect. The matchers that work on finders are these:
findsOneWidget: exactly one match.findsNothing: zero matches.findsWidgets: one or more matches.findsNWidgets(n): exactlynmatches.findsAtLeastNWidgets(n):nor more matches.
Always choose the strictest matcher that is true. findsWidgets passes when a bug produces three copies of a row, but findsNWidgets(2) does not.
testWidgets('shows the empty state and no rows', (tester) async {
await tester.pumpWidget(wrap(const TodoList(items: [])));
expect(find.text('Nothing to do'), findsOneWidget);
expect(find.byType(ListTile), findsNothing);
expect(find.byKey(const Key('add_button')), findsOneWidget);
expect(find.byTooltip('Add todo'), findsOneWidget);
});A passing findsNothing also tests an absence, so pair it with a positive check, as above. Otherwise a typo in the finder passes silently.
Asserting on widget properties
A finder tells you whether a widget exists. To check its configuration, pull the widget out and use ordinary matchers.
tester.widget<T>(finder)returns the single matching widget as typeT.tester.widgetList<T>(finder)returns all matches.tester.element(finder)returns theElement, which gives access toBuildContext.
testWidgets('the add button is enabled and has an icon', (tester) async {
await tester.pumpWidget(wrap(const TodoList(items: ['Milk'])));
final fab = tester.widget<FloatingActionButton>(
find.byKey(const Key('add_button')),
);
expect(fab.onPressed, isNotNull);
final icons = tester.widgetList<Icon>(find.byType(Icon)).toList();
expect(icons.map((i) => i.icon), contains(Icons.add));
});Here isNotNull and contains are general matchers from the matcher package, which flutter_test re-exports. You can combine them with finders freely, because tester.widget returns a normal Dart object.
Common errors
Too many or too few elements
tester.widget and similar methods throw a StateError when the finder matches zero widgets or more than one. The message begins with "Bad state" and "No element" or "Too many elements". The fix is to make the finder more specific, for example with find.descendant or a key.
Items that are not built
A ListView built from a children list is still lazy. Rows outside the visible area, plus a small cache margin, are never created. A finder cannot see a widget that does not exist.
testWidgets('a far-away row is not built until scrolled to', (tester) async {
final items = [for (var i = 0; i < 100; i++) 'Item $i'];
await tester.pumpWidget(wrap(TodoList(items: items)));
expect(find.text('Item 99'), findsNothing);
await tester.scrollUntilVisible(find.text('Item 99'), 500);
expect(find.text('Item 99'), findsOneWidget);
});scrollUntilVisible drags the first Scrollable by 500 logical pixels at a time until the finder matches. If the list is not the first scrollable, pass scrollable: with a finder for it.
Offstage widgets
By default finders skip widgets that are offstage, such as the hidden pages of an IndexedStack. Pass skipOffstage: false to a finder such as find.text('Settings', skipOffstage: false) to include them. This differs from the lazy-list case: an offstage widget exists but is hidden, while an unbuilt widget does not exist at all.
Matching the wrong text
find.text compares the full string. 'Milk' does not match 'Milk, 2 litres'. Use find.textContaining, or check the exact string your widget builds, including punctuation and spaces. For text drawn by a raw RichText widget, pass findRichText: true.
Private classes
Test code cannot name a class that starts with an underscore, so find.byType(_CounterPageState) does not compile. Find the public widget, or give the private one a key.
Putting it together
A solid widget test reads like a short specification: build the widget in a known state, check the visible result with the strictest finder and matcher, and inspect widget properties only when the property is the behavior. Chapter by chapter, the next step is to change the state of the widget by tapping and typing, then to re-run these same finders against the updated tree.
Exercise
A test contains expect(find.byType(ListTile), findsWidgets); and always passes, even after a bug makes the list render each item twice. What change makes the test catch this bug, and why would find.text('Milk') with findsOneWidget also catch it?
Show answer
Replace findsWidgets with findsNWidgets(n), where n is the number of items, because findsWidgets accepts any count of one or more. find.text('Milk') with findsOneWidget fails when the row is duplicated, since two Text widgets would then match and findsOneWidget requires exactly one.
Exercise
You write tester.widget<Text>(find.text('Milk')) in a test and it throws "Too many elements". Name two ways to fix it.
Show answer
Make the finder match one widget, for example find.descendant(of: find.byKey(const Key('row_milk')), matching: find.text('Milk')) or find.widgetWithText(ListTile, 'Milk'). Alternatively select one match with .first or .at(0), after you have confirmed that several matches are expected.