$npx -y skills add flutter/agent-plugins --skill flutter-add-widget-testImplement a component-level test using WidgetTester to verify UI rendering and user interactions (tapping, scrolling, entering text). Use when validating that a specific widget displays correct data and responds to events as expected.
| 1 | # Writing Flutter Widget Tests |
| 2 | |
| 3 | ## Contents |
| 4 | - [Setup & Configuration](#setup--configuration) |
| 5 | - [Core Components](#core-components) |
| 6 | - [Workflow: Implementing a Widget Test](#workflow-implementing-a-widget-test) |
| 7 | - [Interaction & State Management](#interaction--state-management) |
| 8 | - [Examples](#examples) |
| 9 | |
| 10 | ## Setup & Configuration |
| 11 | |
| 12 | Ensure the testing environment is properly configured before authoring widget tests. |
| 13 | |
| 14 | 1. Add the `flutter_test` dependency to the `dev_dependencies` section of `pubspec.yaml`. |
| 15 | 2. Place all test files in the `test/` directory at the root of the project. |
| 16 | 3. Suffix all test file names with `_test.dart` (e.g., `widget_test.dart`). |
| 17 | |
| 18 | ## Core Components |
| 19 | |
| 20 | Utilize the following `flutter_test` components to interact with and validate the widget tree: |
| 21 | |
| 22 | * **`WidgetTester`**: The primary interface for building and interacting with widgets in the test environment. Provided automatically by the `testWidgets()` function. |
| 23 | * **`Finder`**: Locates widgets in the test environment (e.g., `find.text('Submit')`, `find.byType(TextField)`, `find.byKey(Key('submit_btn'))`). |
| 24 | * **`Matcher`**: Verifies the presence or state of widgets located by a `Finder` (e.g., `findsOneWidget`, `findsNothing`, `findsNWidgets(2)`, `matchesGoldenFile`). |
| 25 | |
| 26 | ## Workflow: Implementing a Widget Test |
| 27 | |
| 28 | Copy the following checklist to track progress when implementing a new widget test. |
| 29 | |
| 30 | ### Task Progress |
| 31 | - [ ] **Step 1: Define the test.** Use `testWidgets('description', (WidgetTester tester) async { ... })`. |
| 32 | - [ ] **Step 2: Build the widget.** Call `await tester.pumpWidget(MyWidget())` to render the UI. Wrap the widget in a `MaterialApp` or `Directionality` widget if it requires inherited directional or theme data. |
| 33 | - [ ] **Step 3: Locate elements.** Instantiate `Finder` objects for the target widgets. |
| 34 | - [ ] **Step 4: Verify initial state.** Use `expect(finder, matcher)` to validate the initial render. |
| 35 | - [ ] **Step 5: Simulate interactions.** Execute gestures or inputs (e.g., `await tester.tap(buttonFinder)`). |
| 36 | - [ ] **Step 6: Rebuild the tree.** Call `await tester.pump()` or `await tester.pumpAndSettle()` to process state changes. |
| 37 | - [ ] **Step 7: Verify updated state.** Use `expect()` to validate the UI after the interaction. |
| 38 | - [ ] **Step 8: Run and validate.** Execute `flutter test test/your_test_file_test.dart`. |
| 39 | - [ ] **Step 9: Feedback Loop.** Review test output -> identify failing matchers -> adjust widget logic or test assertions -> re-run until passing. |
| 40 | |
| 41 | ## Interaction & State Management |
| 42 | |
| 43 | Apply the following conditional logic based on the type of interaction or state change being tested: |
| 44 | |
| 45 | * **If testing static rendering:** Call `await tester.pumpWidget()` once, then immediately run `expect()` assertions. |
| 46 | * **If testing standard state changes (e.g., button taps):** |
| 47 | 1. Call `await tester.tap(finder)`. |
| 48 | 2. Call `await tester.pump()` to trigger a single frame rebuild. |
| 49 | * **If testing animations, transitions, or asynchronous UI updates:** |
| 50 | 1. Trigger the action (e.g., `await tester.drag(finder, Offset(500, 0))`). |
| 51 | 2. Call `await tester.pumpAndSettle()` to repeatedly pump frames until no more frames are scheduled (animation completes). |
| 52 | * **If testing text input:** Call `await tester.enterText(textFieldFinder, 'Input string')`. |
| 53 | * **If testing items in a dynamic or long list:** Call `await tester.scrollUntilVisible(itemFinder, 500.0, scrollable: listFinder)` to ensure the target widget is rendered before interacting with it. |
| 54 | |
| 55 | ## Examples |
| 56 | |
| 57 | ### High-Fidelity Widget Test Implementation |
| 58 | |
| 59 | **Target Widget (`lib/todo_list.dart`):** |
| 60 | ```dart |
| 61 | import 'package:flutter/material.dart'; |
| 62 | |
| 63 | class TodoList extends StatefulWidget { |
| 64 | const TodoList({super.key}); |
| 65 | |
| 66 | @override |
| 67 | State<TodoList> createState() => _TodoListState(); |
| 68 | } |
| 69 | |
| 70 | class _TodoListState extends State<TodoList> { |
| 71 | final todos = <String>[]; |
| 72 | final controller = TextEditingController(); |
| 73 | |
| 74 | @override |
| 75 | Widget build(BuildContext context) { |
| 76 | return MaterialApp( |
| 77 | home: Scaffold( |
| 78 | body: Column( |
| 79 | children: [ |
| 80 | TextField(controller: controller), |
| 81 | Expanded( |
| 82 | child: ListView.builder( |
| 83 | itemCount: todos.length, |
| 84 | itemBuilder: (context, index) { |
| 85 | final todo = todos[index]; |
| 86 | return Dismissible( |
| 87 | key: Key('$todo$index'), |
| 88 | onDismissed: (_) => setState(() => todos.removeAt(index)), |
| 89 | child: ListTile(title: Text(todo)), |
| 90 | ); |
| 91 | }, |
| 92 | ), |
| 93 | ), |
| 94 | ], |
| 95 | ), |
| 96 | floatingAction |