Sub topic 4
Asserting with findsOneWidget, findsNothing and friends
This chapter covers the matchers that turn a finder into a pass or fail result. It assumes you can write a basic testWidgets test, call pumpWidget, and create a finder such as find.text('Save'). You should also know that flutter_test is in your dev_dependencies.
What a finder matcher does
A finder describes a search. It does not run the search until something asks for the result. The expect function asks, and the matcher you pass decides whether the number of matches is acceptable.
expect(find.text('Save'), findsOneWidget);When this line runs, expect evaluates the finder against the widget tree that exists right now. It collects the matching elements and gives that collection to findsOneWidget. If exactly one element matches, the test continues. Otherwise it throws a TestFailure.
Two details follow from this.
- The search reflects the tree at the moment of
expect. If you changed state and did not callpump, the tree is stale, and the assertion checks the old tree. - A finder is reusable. You can store it in a variable and assert on it before and after an interaction. Each
expectre-runs the search.
The core matchers
flutter_test provides these matchers for finders.
| Matcher | Passes when | Typical use |
|---|---|---|
| `findsOneWidget` | Exactly one match | A unique label, button, or title |
| `findsNothing` | Zero matches | A widget was removed, hidden, or never built |
| `findsWidgets` | One or more matches | Repeated items where the count does not matter |
| `findsNWidgets(n)` | Exactly `n` matches | A list with a known number of rows |
| `findsAtLeastNWidgets(n)` | `n` or more matches | A list that must show at least a few items |
Each one fails with a message that states the expected count and shows what was found. Read those messages. They tell you whether your finder was too broad, too narrow, or pointed at an old tree.
findsOneWidget and findsNothing
These two do most of the work in a typical test. A common pattern checks one state, acts, then checks the next state.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('$_count')),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
void main() {
testWidgets('counter increments when the button is tapped',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Counter()));
expect(find.text('0'), findsOneWidget);
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}The test asserts findsOneWidget for '0' first. After the tap and pump, it asserts findsNothing for '0' and findsOneWidget for '1'. Checking that the old value is gone is as important as checking the new one. Without the findsNothing line, a bug that displays both values would pass.
findsWidgets and findsNWidgets
Use findsWidgets when you only need to know that something appears. Use findsNWidgets when the count is part of the behavior.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows one tile for each item', (tester) async {
const names = ['Ada', 'Grace', 'Linus'];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
for (final name in names) ListTile(title: Text(name)),
],
),
),
),
);
expect(find.byType(ListTile), findsNWidgets(3));
expect(find.byType(ListTile), findsWidgets);
expect(find.byType(ListTile), findsAtLeastNWidgets(2));
expect(find.text('Margaret'), findsNothing);
});
}Every assertion here passes. findsWidgets is the weakest of the three on ListTile. It would also pass with 30 tiles. Prefer findsNWidgets whenever you know the number, because it catches duplicated rows.
Matching counts exactly
Many beginner failures come from a count that is higher than expected. The message Expected: exactly one matching candidate, Actual: _TextFinder:<2 widgets with text "Save"> means the finder matched twice.
Common causes:
- The same text appears in an
AppBartitle and in a button. - A route you pushed earlier is still in the tree under the new one. Both routes build, so both match.
- A
TooltiporSemanticswidget adds a secondTextdescendant. - A
TextFieldshows itshintTextand itslabelTextat the same time.
When a finder is too broad, narrow it instead of switching to findsWidgets. Weakening the matcher hides the problem. Narrowing the finder documents what you mean.
// 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,
);
// Matchers that go with them:
// expect(saveButton, findsOneWidget);
// expect(titleInAppBar, findsOneWidget);
// expect(disabledButtons, findsNWidgets(2));Here widgetWithText limits the match to an ElevatedButton that contains the text. descendant limits it to the AppBar subtree. byWidgetPredicate lets you test any property, such as a disabled onPressed.
Offstage, hidden, and skipped widgets
A finder's default behavior hides some traps for the matchers.
By default, finders skip widgets that are Offstage. A widget wrapped in Offstage(offstage: true, ...) is built, but find.text will not report it, so findsNothing passes even though the widget exists in the tree. Pass skipOffstage: false to include it.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('offstage widgets are skipped by default', (tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Offstage(
offstage: true,
child: Text('Secret'),
),
),
);
expect(find.text('Secret'), findsNothing);
expect(find.text('Secret', skipOffstage: false), findsOneWidget);
});
}Other cases behave differently:
Visibility(visible: false)removes its child from the tree by default, so the finder finds nothing.Opacity(opacity: 0)keeps the child in the tree and visible to finders. The widget is invisible to a user, butfindsOneWidgetpasses.- A widget scrolled far off screen inside a lazy list such as
ListView.buildermay not be built at all, sofindsNothingpasses for the wrong reason.
The finders answer "is it in the tree," not "can the user see it." Keep that in mind when a test passes but the screen looks wrong.
Checking a property after finding the widget
The count matchers only check presence. To check what a widget holds, find it and read it with tester.widget. Pair it with a normal matcher such as equals or isTrue.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class GreetingForm extends StatefulWidget {
const GreetingForm({super.key});
@override
State<GreetingForm> createState() => _GreetingFormState();
}
class _GreetingFormState extends State<GreetingForm> {
final _controller = TextEditingController();
String _greeting = '';
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(key: const Key('name'), controller: _controller),
ElevatedButton(
key: const Key('greet'),
onPressed: () =>
setState(() => _greeting = 'Hello, ${_controller.text}'),
child: const Text('Greet'),
),
Text(_greeting, key: const Key('greeting')),
],
);
}
}
void main() {
testWidgets('greets the name that was typed', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: GreetingForm())),
);
await tester.enterText(find.byKey(const Key('name')), 'Ada');
await tester.tap(find.byKey(const Key('greet')));
await tester.pump();
final greeting = tester.widget<Text>(find.byKey(const Key('greeting')));
expect(greeting.data, 'Hello, Ada');
});
}tester.widget<Text> requires exactly one match and throws if there are none or several. This makes it a strict check in its own right. If you want to read the first match of many, use tester.firstWidget instead.
Choosing the right matcher
Use these rules when you decide which assertion to write.
- Use
findsOneWidgetfor anything that should be unique on screen. - Use
findsNothingto prove removal, and place it right after the action that should cause it. - Use
findsNWidgets(n)when the count is a requirement, such as one row per record. - Use
findsWidgetsonly when the count is truly irrelevant. - Read a property with
tester.widgetwhen presence is not enough.
Common mistakes
- Asserting before
pump. Aftertap, the tree has not rebuilt.expect(find.text('1'), findsOneWidget)fails because the screen still shows0. Callawait tester.pump()first. - Using
findsNothingas the only check. A typo in the finder, such asfind.text('Sav'), also givesfindsNothing. Pair negative assertions with a positive one that proves the screen is in the expected state. - Forgetting
await.tester.tapreturns aFuture. Withoutawait, the assertion can run before the tap happens. - Matching text that is not a plain
Text.find.textmatchesTextandEditableTextcontent. A string inside a custom painter or an image will not match.
How the matcher sees the tree
The diagram shows where each step of a typical assertion happens.
The search at step C uses the tree as of the last pump. Everything before that point is bookkeeping, and everything after is a count comparison.
Exercise
A test taps a button that should remove a banner reading "Offline". After await tester.tap(find.text('Retry')), the test runs expect(find.text('Offline'), findsNothing) and fails, although the app works correctly when run by hand. What is the most likely cause, and how do you fix it?
Show answer
The widget tree has not rebuilt yet. tap triggers setState, but the frame that removes the banner is not drawn until you call await tester.pump() (or pumpAndSettle if an animation or async work is involved). Add await tester.pump(); between the tap and the expect.
Exercise
A screen has an AppBar titled "Inbox" and a body that also contains a heading "Inbox". expect(find.text('Inbox'), findsOneWidget) fails. Write one finder that matches only the heading in the app bar, and name the matcher you would use with it.
Show answer
Use find.descendant(of: find.byType(AppBar), matching: find.text('Inbox')) with findsOneWidget. The descendant finder restricts the search to the AppBar subtree, so the body heading is not counted.