Sub topic 13
Writing your first widget test
This chapter assumes you have a generated project named my_first_app with the counter app from the previous chapters in lib/main.dart. It also assumes you can run commands in a terminal and know basic Dart syntax, including async and await. You will write a widget test, run it, and learn how to read its failures.
What a widget test is
A widget test (also called a component test) builds a widget in a simulated environment, interacts with it, and checks what it displays. It runs on your machine in the Dart VM. It does not start an emulator, a browser, or a real device, so it finishes in milliseconds to a few seconds.
Flutter projects use three kinds of automated tests:
| Kind | What it checks | Needs a device | Typical speed |
|---|---|---|---|
| Unit test | One function or class, with no UI | No | Very fast |
| Widget test | One widget or screen, including taps and text | No | Fast |
| Integration test | The whole app running on a device or emulator | Yes | Slow |
Widget tests sit in the middle. They exercise your real build() methods and your real setState calls, but they skip the cost of a real screen. The counter app is a good first target because tapping the button changes the text, and a test can observe that change.
Where tests live
flutter create generates a test/ folder with a sample widget_test.dart. The test runner finds files that end in _test.dart inside test/. The flutter_test package, which provides the test tools, is already listed under dev_dependencies in pubspec.yaml, so you do not need to add it.
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^4.0.0The exact version of flutter_lints depends on your Flutter release. The flutter_test entry matters here because it points at the SDK itself, so the testing tools always match your Flutter version.
The test
Replace the contents of test/widget_test.dart with this:
import 'package:flutter_test/flutter_test.dart';
import 'package:my_first_app/main.dart';
void main() {
testWidgets('counter increments when the button is tapped',
(WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
expect(find.text('Taps: 0'), findsOneWidget);
await tester.tap(find.byType(FloatingActionButton));
await tester.pump();
expect(find.text('Taps: 1'), findsOneWidget);
});
}The import package:my_first_app/main.dart uses the package name from the name: field in pubspec.yaml. If you named your project something else, change that line to match, or the test will fail to compile.
Reading the test line by line
The test follows an arrange, act, assert pattern.
testWidgets(description, callback)declares one test. The description appears in the output. The callback receives aWidgetTester, which is your remote control for the simulated app. The callback isasyncbecause most tester actions return aFuture.await tester.pumpWidget(const MyApp())is the arrange step. It builds the widget and renders the first frame. Without this call, nothing exists to inspect.expect(find.text('Taps: 0'), findsOneWidget)is the first assert. It confirms the starting state.await tester.tap(find.byType(FloatingActionButton))is the act step. It sends a tap to the center of the matching widget.await tester.pump()rebuilds the widget tree. This line is easy to forget, and the next section explains why it matters.- The final
expectis the second assert. It confirms the text changed.
Finders and matchers
A finder locates widgets in the tree. A matcher states how many you expect.
| Finder | Finds |
|---|---|
| `find.text('Taps: 0')` | A `Text` widget with exactly that string |
| `find.byType(FloatingActionButton)` | Widgets of that class |
| `find.byIcon(Icons.add)` | An `Icon` showing that icon |
| `find.byKey(const Key('save'))` | A widget given that `Key` |
| `find.byTooltip('Increment')` | A widget with that tooltip |
| Matcher | Passes when |
|---|---|
| `findsOneWidget` | Exactly one match exists |
| `findsNothing` | Zero matches exist |
| `findsNWidgets(3)` | Exactly three matches exist |
| `findsWidgets` | One or more matches exist |
find.text matches the whole string. find.text('Taps') would not match 'Taps: 0'. Use find.textContaining('Taps') for partial matches.
Why pump is required
In a real app, Flutter schedules a new frame after setState. In a test, time does not move on its own. The tester controls the clock, and no frame is drawn until you ask for one. The tap call runs _increment, so _count becomes 1 and the framework marks the widget dirty. The screen still shows the old text until you call pump().
If you remove the pump() line, the last assertion fails because Taps: 1 has not been built yet.
pump, pumpAndSettle, and animations
pump() advances one frame. It also accepts a duration, for example pump(const Duration(milliseconds: 300)), which moves the fake clock forward before building the frame.
pumpAndSettle() calls pump repeatedly until no frames are scheduled. Use it after actions that start animations, such as opening a dialog or navigating to another route. It has a limit: if something animates forever (a progress spinner, for example), it never settles and throws a timeout error. In that case, use pump() with an explicit duration instead.
The counter app has no animations that matter here, so a single pump() is enough.
Running the tests
Run every test in the project:
flutter testTo run one file or filter by name:
flutter test test/widget_test.dart
flutter test --plain-name "counter increments"A passing run ends with a line like All tests passed!. Your editor also shows run and debug buttons next to each testWidgets call if the Flutter extension is installed.
Reading a failure
Change the final expectation to find.text('Taps: 5') and run the test again. You will see output similar to this:
Expected: exactly one matching candidate
Actual: _TextWidgetFinder:<Found 0 widgets with text "Taps: 5": []>
Which: means none were found but one was expectedThe message tells you which finder ran and how many widgets matched. When a text assertion fails, check these things first:
- The string differs in spacing, capitalization, or punctuation.
- You forgot
pump()after an action that changes state. - The widget is not on screen yet because a route change or animation has not finished.
- The widget is in the tree, but a different one with the same text also exists, which gives
Found 2 widgetsand failsfindsOneWidget.
Common errors
- Test cannot find
MyApp. The import path or package name is wrong. Checkname:inpubspec.yaml. No MediaQuery widget ancestor found. You pumped a widget that needsMaterialAppabove it, such as a bareScaffold. Wrap it:tester.pumpWidget(const MaterialApp(home: MyPage())).- Tapping does nothing. The finder may match a widget that is off screen or covered by another. Call
tester.ensureVisible(finder)first, or check that the finder points at the intended widget. pumpAndSettle timed out. An animation never ends. Replace it withpump(duration).- Default sample test fails. The test that
flutter creategenerates may refer to a different class or text than your edited app. Replace it, as you did above.
Extending the test
A second test in the same main() can check a different behavior. Tests do not share state, because each testWidgets call builds its own widget tree.
import 'package:flutter_test/flutter_test.dart';
import 'package:my_first_app/main.dart';
void main() {
testWidgets('counter increments when the button is tapped',
(WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
expect(find.text('Taps: 0'), findsOneWidget);
await tester.tap(find.byType(FloatingActionButton));
await tester.pump();
expect(find.text('Taps: 1'), findsOneWidget);
});
testWidgets('counter reaches 3 after three taps',
(WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
for (var i = 0; i < 3; i++) {
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
}
expect(find.text('Taps: 3'), findsOneWidget);
expect(find.text('Taps: 0'), findsNothing);
});
}This version imports only flutter_test, which re-exports the Material widgets needed for Icons.add? It does not: Icons comes from the Material library. If the analyzer reports Undefined name 'Icons', add import 'package:flutter/material.dart'; at the top. Adding it is safe and makes the file self-contained.
Exercise
In the counter test, what happens if you delete the await tester.pump(); line after the tap, and why?
Show answer
The final expect(find.text('Taps: 1'), findsOneWidget) fails. The tap runs _increment, which calls setState and marks the widget dirty, but the test clock does not advance on its own. No new frame is built until pump() is called, so the tree still shows Taps: 0.
Exercise
Write a test that taps the button twice and then expects Taps: 2. Which finder would you use if you wanted it to keep working after the button's icon changes, and what must you add to the app code to support it?
Show answer
Give the button a key in lib/main.dart, for example FloatingActionButton(key: const Key('increment'), ...). In the test, call await tester.tap(find.byKey(const Key('increment'))); followed by await tester.pump();, twice, then expect(find.text('Taps: 2'), findsOneWidget);. A key stays the same when the icon, tooltip, or label changes.