Sub topic 7
Reading widget properties and state
Finders and matchers tell you whether a widget is on screen. Sometimes you also need to know how it is configured: whether a button is enabled, which style a Text uses, what a controller holds, or what a State object remembers. This chapter covers how WidgetTester gives you that access and where it stops being a good idea.
This chapter assumes you can write a basic testWidgets test and use pumpWidget, find.byKey, tap, enterText and pump. It also assumes you know the difference between a Widget and its State.
From finder to widget, element and state
A finder describes a search. It does not hold a result until the tester evaluates it against the current tree. Flutter keeps three related objects for each piece of UI:
- The widget is an immutable configuration, such as a
Textwith itsdataandstyle. - The element is the live node in the tree. It points to its widget and, for stateful widgets, to its state.
- The state is the mutable object behind a
StatefulWidget.
The tester has a method for each of these layers.
| Method | Returns | Fails when |
|---|---|---|
| `tester.widget<T>(finder)` | The single matching widget, cast to `T` | Zero or several matches, or the type is wrong |
| `tester.firstWidget<T>(finder)` | The first match | No matches |
| `tester.widgetList<T>(finder)` | All matches as an `Iterable<T>` | The type is wrong |
| `tester.element(finder)` | The single matching `Element` | Zero or several matches |
| `tester.state<T>(finder)` | The `State` of the single matching stateful widget | Zero or several matches, or the type is wrong |
| `tester.getSize(finder)` | The rendered `Size` | Zero or several matches |
The widget, element and state methods require exactly one match. That strictness is useful, because a finder that matches two widgets usually means your test is looking at the wrong thing.
Reading widget properties
Use tester.widget<T> when the property you care about is part of the widget's configuration. The example below tests a form whose button is disabled until the field has text.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class SubmitForm extends StatefulWidget {
const SubmitForm({super.key});
@override
State<SubmitForm> createState() => SubmitFormState();
}
class SubmitFormState extends State<SubmitForm> {
final controller = TextEditingController();
int submitCount = 0;
bool get canSubmit => controller.text.trim().isNotEmpty;
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
key: const Key('name'),
controller: controller,
onChanged: (_) => setState(() {}),
),
ElevatedButton(
key: const Key('submit'),
onPressed: canSubmit ? () => setState(() => submitCount++) : null,
child: const Text('Submit'),
),
Text(
'Submitted $submitCount',
key: const Key('status'),
style: const TextStyle(fontWeight: FontWeight.bold),
),
],
);
}
}
void main() {
testWidgets('button enables after typing and state tracks submits',
(tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: SubmitForm())),
);
ElevatedButton button() =>
tester.widget<ElevatedButton>(find.byKey(const Key('submit')));
// A null onPressed means the button is disabled.
expect(button().onPressed, isNull);
await tester.enterText(find.byKey(const Key('name')), 'Ada');
await tester.pump();
expect(button().onPressed, isNotNull);
await tester.tap(find.byKey(const Key('submit')));
await tester.pump();
final status = tester.widget<Text>(find.byKey(const Key('status')));
expect(status.data, 'Submitted 1');
expect(status.style?.fontWeight, FontWeight.bold);
final field = tester.widget<TextField>(find.byKey(const Key('name')));
expect(field.controller!.text, 'Ada');
final state = tester.state<SubmitFormState>(find.byType(SubmitForm));
expect(state.submitCount, 1);
});
}Some details in this test are easy to get wrong.
button()is a function, not a variable. Each call looks up the widget again. This matters because of the next point.- A widget is a snapshot. After
pump, the framework builds a newElevatedButtonobject. A variable that holds the old one still shows the oldonPressed. Re-read after everypump. - A disabled Material button has
onPressed == null. Checking this is more direct than tapping the button and seeing nothing happen. Text.dataisnullwhen the text was built withText.rich. In that case readtextSpaninstead, or usefind.textContainingwithfindRichText: true.
Matching several properties at once
When you check more than one property, isA<T>().having(...) gives a better failure message than a chain of separate expect calls.
expect(
tester.widget<Text>(find.byKey(const Key('status'))),
isA<Text>()
.having((t) => t.data, 'data', 'Submitted 1')
.having((t) => t.style?.fontWeight, 'weight', FontWeight.bold),
);If one property is wrong, the output names that property and prints the expected and actual values.
Reading state objects
tester.state<T>(finder) finds the element for the stateful widget and returns its State. The finder must resolve to the stateful widget itself, such as find.byType(SubmitForm). A finder for one of its children, such as find.text('Submit'), fails because that element is not the one that owns the state.
Two limits apply to state access.
Tmust be a type the test file can name. Dart makes names that start with an underscore private to their library, and files intest/are separate libraries. In the form above,SubmitFormStateis public for that reason. If you must expose a state class only for tests, annotate it with@visibleForTestingfrompackage:meta/meta.dart.- A state test checks implementation, not behavior. If you rename
submitCounttosubmissions, the test breaks even though the screen looks identical.
For that reason, prefer asserting on what the user sees, such as the Text. Reach for state only when the value has no visible output, such as a controller you want to confirm was disposed or a flag that triggers a later effect.
Reading from the build context
Some values do not live on a widget you can find. Themes, media queries and locale come from inherited widgets, and you read them through a BuildContext. The tester can give you one with tester.element, because an Element is a BuildContext.
The same test can also check layout size with getSize.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('reads size and theme from the tree', (tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const Scaffold(
body: Center(
child: SizedBox(
key: Key('box'),
width: 120,
height: 40,
child: Text('Hi'),
),
),
),
),
);
expect(tester.getSize(find.byKey(const Key('box'))), const Size(120, 40));
final context = tester.element(find.byKey(const Key('box')));
expect(Theme.of(context).colorScheme.brightness, Brightness.light);
});
}getSize reports the size after layout, in logical pixels. The default test surface is 800 by 600 logical pixels, so size assertions are stable across machines. Companion methods include getTopLeft, getCenter and getRect. Use them to check position or overlap, for example that a button is below a header.
Inspecting every match
Sometimes you want to look at all matches instead of one. widgetList returns them in tree order, and finder.evaluate() returns the Element objects directly.
final tiles = tester.widgetList<ListTile>(find.byType(ListTile));
expect(tiles.map((t) => (t.title as Text).data).toList(), ['A', 'B', 'C']);
expect(find.byType(ListTile).evaluate().length, 3);For plain counts, findsNWidgets(3) is shorter and gives a better message. Use widgetList when you need the contents, such as checking order.
Common errors
- Stale reference. You stored a widget in a variable before
pumpand asserted on it afterward. Re-runtester.widgetafter each rebuild. - Wrong finder level.
tester.statewas givenfind.text(...)instead of the stateful widget's type or key. - Type mismatch.
tester.widget<Text>(find.byKey(...))fails with a cast error when the key sits on aPaddingorContainerthat wraps theText. Put the key on the widget you read, or usefind.descendant. - Several matches.
widgetfound twoTextwidgets with the same string, for example one in anAppBarand one in the body. Narrow the finder withfind.descendantor a key. - Private state class.
_FormStatecannot be named fromtest/. Make it public or assert through the UI.
Exercise
A test stores final button = tester.widget<ElevatedButton>(find.byKey(const Key('submit'))); before typing into a field, then calls await tester.pump() and asserts expect(button.onPressed, isNotNull). The assertion fails even though the button is enabled on screen. Why, and how do you fix it?
Show answer
The button variable holds the widget object from the first build. A widget is an immutable snapshot, and pump creates a new ElevatedButton with the updated onPressed, so the stored object still shows null. Fix it by calling tester.widget<ElevatedButton>(...) again after pump, or by wrapping the lookup in a small function such as button() and calling it each time you assert.
Exercise
Your test calls tester.state<_CartState>(find.byType(CartPage)) and fails to compile. Name two ways to fix it, and say which one you would choose.
Show answer
One fix is to make the class public, for example CartState, optionally annotated with @visibleForTesting, so the test file can name it. The other is to avoid state access and assert on what the page shows, such as the item count in a Text found by key. Prefer the second, because it survives refactoring of the state class. Use the first only when the value has no visible output.