Sub topic 2
Tapping and entering text
This chapter assumes you can write a testWidgets test, build a widget with pumpWidget, locate widgets with finders such as find.text and find.byKey, and check results with findsOneWidget and findsNothing.
Tapping and entering text
tester.tap(finder) sends a pointer tap to the center of the matched widget. It does not rebuild the tree. Call pump afterward so the framework processes the state change.
tester.enterText(finder, text) taps the target field, then replaces its contents with text. The finder should match a TextField or TextFormField.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('greets the name that was typed', (tester) async {
final controller = TextEditingController();
String greeting = '';
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Column(children: [
TextField(key: const Key('name'), controller: controller),
ElevatedButton(
key: const Key('greet'),
onPressed: () => greeting = 'Hello, ${controller.text}',
child: const Text('Greet'),
),
]),
),
));
await tester.enterText(find.byKey(const Key('name')), 'Ada');
await tester.tap(find.byKey(const Key('greet')));
expect(greeting, 'Hello, Ada');
});
}Rebuilding the tree: pump versus pumpAndSettle
pump() advances one frame. pump(Duration) advances the fake clock by a fixed amount, which suits an animation with a known length. pumpAndSettle() keeps pumping until no frames are scheduled.
pumpAndSettle() fails with a timeout if an animation never stops, such as a looping CircularProgressIndicator.
Reading widget properties and state
tester.widget<T>(finder) returns the widget instance that matches the finder. Use it to read properties that matchers cannot check directly.
final text = tester.widget<Text>(find.byKey(const Key('greeting')));
expect(text.data, 'Hello, Ada');tester.state<T>(finder) returns the State object of a StatefulWidget. Use it to inspect private fields when the widget does not expose them.
Scrolling lists and dragging
tester.drag(finder, offset) moves a widget by the given offset. A negative dy scrolls content up.
ListView.builder builds only the items near the viewport, so an off-screen item may not exist in the tree yet. scrollUntilVisible scrolls in steps until the finder matches.
testWidgets('scrolls to an item that is not built yet', (tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: 100,
itemBuilder: (context, i) => ListTile(title: Text('Item $i')),
),
),
));
expect(find.text('Item 80'), findsNothing);
await tester.scrollUntilVisible(find.text('Item 80'), 500);
expect(find.text('Item 80'), findsOneWidget);
});Exercise
A test taps a button that calls setState, then immediately checks for the new text. Why might the check fail?
Show answer
Tapping does not rebuild the tree. The test must call pump (or pumpAndSettle) after the tap so the framework builds the new frame before the expect runs.