Sub topic 15
Testing taps and drags with flutter_test
This chapter shows how to simulate taps, long presses and drags in a widget test and check the result. It assumes you can write a basic Dart test, you know setState, and you have built the buttons and gesture widgets from the earlier chapters. Everything below runs with flutter test.
How a widget test drives your UI
A widget test runs your widgets in a headless test environment. No device or emulator is involved, and the framework does not draw frames on its own. You tell it when to build and when to advance time.
The testWidgets function gives you a WidgetTester. The usual cycle is:
Each step has a job:
pumpWidgetbuilds the tree once.- A
Finderlocates a widget. - An action method sends pointer events to it.
pumpruns the rebuild thatsetStatescheduled.expectchecks the new state.
You can repeat the cycle in one test, as the first example does.
Testing a tap
This test is self-contained. It includes the counter button from the button chapters so you can run it as one file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class CounterButton extends StatefulWidget {
const CounterButton({super.key});
@override
State<CounterButton> createState() => _CounterButtonState();
}
class _CounterButtonState extends State<CounterButton> {
int _count = 0;
@override
Widget build(BuildContext context) {
return FilledButton(
onPressed: () => setState(() => _count++),
child: Text('Pressed $_count times'),
);
}
}
void main() {
testWidgets('tapping the button increments the count', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: CounterButton())),
);
expect(find.text('Pressed 0 times'), findsOneWidget);
await tester.tap(find.byType(FilledButton));
await tester.pump();
expect(find.text('Pressed 1 times'), findsOneWidget);
});
}Wrap the widget under test in MaterialApp and Scaffold. Buttons need a Material ancestor, Text needs a Directionality, and MaterialApp provides all of these.
tester.tap sends a pointer down and a pointer up at the center of the widget the finder matched. The onPressed callback runs immediately, but the rebuild does not. Without pump, the old label is still in the tree and the second expect fails.
pump, pumpAndSettle and time
| Method | What it does | Use it when |
|---|---|---|
| `pump()` | Builds one frame | A `setState` changed the tree |
| `pump(duration)` | Advances the fake clock, then builds a frame | A timer or a fixed delay matters |
| `pumpAndSettle()` | Keeps pumping until no frames are scheduled | A finite animation should finish |
Testing the disabled state
A disabled button has onPressed == null. You can check that property directly instead of tapping and hoping nothing happens. A good test does both.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class SubmitForm extends StatefulWidget {
const SubmitForm({super.key, required this.onSubmit});
final VoidCallback onSubmit;
@override
State<SubmitForm> createState() => _SubmitFormState();
}
class _SubmitFormState extends State<SubmitForm> {
final _controller = TextEditingController();
@override
void initState() {
super.initState();
_controller.addListener(() => setState(() {}));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(controller: _controller),
ElevatedButton(
onPressed: _controller.text.isEmpty ? null : widget.onSubmit,
child: const Text('Submit'),
),
],
);
}
}
void main() {
testWidgets('submit is disabled until text is entered', (tester) async {
var submitted = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: SubmitForm(onSubmit: () => submitted++)),
),
);
ElevatedButton button() =>
tester.widget<ElevatedButton>(find.byType(ElevatedButton));
expect(button().onPressed, isNull);
await tester.tap(find.byType(ElevatedButton));
expect(submitted, 0);
await tester.enterText(find.byType(TextField), 'hello');
await tester.pump();
expect(button().onPressed, isNotNull);
await tester.tap(find.byType(ElevatedButton));
expect(submitted, 1);
});
}The button() helper looks the widget up again on each call. A widget object you stored earlier would be stale after a rebuild. enterText changes the controller, which triggers the listener, and pump applies the rebuild.
Tap, double tap and long press
GestureDetector with several callbacks needs care in tests, because the framework waits to see whether a second tap follows.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('recognizes tap, double tap and long press', (tester) async {
final events = <String>[];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => events.add('tap'),
onDoubleTap: () => events.add('double tap'),
onLongPress: () => events.add('long press'),
child: const SizedBox(
width: 120,
height: 120,
child: Center(child: Text('Tap me')),
),
),
),
),
),
);
// A single tap is only reported after the double-tap window closes.
await tester.tap(find.text('Tap me'));
await tester.pump(kDoubleTapTimeout);
expect(events, ['tap']);
// Two taps close together form a double tap.
await tester.tap(find.text('Tap me'));
await tester.pump(kDoubleTapMinTime);
await tester.tap(find.text('Tap me'));
await tester.pump();
expect(events, ['tap', 'double tap']);
await tester.longPress(find.text('Tap me'));
await tester.pump();
expect(events, ['tap', 'double tap', 'long press']);
});
}When onDoubleTap is set, the onTap callback is delayed until kDoubleTapTimeout passes. A test that taps once and asserts immediately will fail even though the app works. This is the gesture arena at work. The tap recognizer cannot win until the double-tap recognizer gives up. Advancing the fake clock with pump is how you let that happen.
tester.longPress holds the pointer down long enough to pass kLongPressTimeout, then releases it.
Testing drags
tester.drag(finder, offset) presses at the center of the widget and moves the pointer by offset. This test uses the draggable box from the drag chapter:
testWidgets('dragging moves the box', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: DraggableBox())),
);
final box = find.descendant(
of: find.byType(DraggableBox),
matching: find.byType(Container),
);
final before = tester.getTopLeft(box);
await tester.drag(box, const Offset(50, 30));
await tester.pump();
final after = tester.getTopLeft(box);
expect(after.dx, greaterThan(before.dx));
expect(after.dy, greaterThan(before.dy));
});getTopLeft reads the position from the render tree, so you test what the user would see, not a private field. The assertions use greaterThan instead of exact numbers because a recognizer ignores the first few pixels of movement (the touch slop) before it decides a drag has started. Assert on direction first. Assert exact values only when you have confirmed them for your recognizer.
For a swipe-to-dismiss list, the test also checks that the data source changed:
testWidgets('swiping an item away removes it', (tester) async {
final items = ['Apple', 'Pear'];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return Dismissible(
key: ValueKey(item),
background: Container(color: Colors.red),
onDismissed: (_) => setState(() => items.removeAt(index)),
child: ListTile(title: Text(item)),
);
},
),
),
),
),
);
await tester.drag(find.text('Apple'), const Offset(500, 0));
await tester.pumpAndSettle();
expect(find.text('Apple'), findsNothing);
expect(find.text('Pear'), findsOneWidget);
});pumpAndSettle is right here because the dismiss animation is finite. If you want a drag with a release velocity, use tester.fling(finder, offset, speed).
Gesture methods at a glance
| Method | Simulates |
|---|---|
| `tap` | Pointer down and up |
| `longPress` | Pointer held past the long-press timeout |
| `drag` | Pointer moves by an offset, then lifts |
| `fling` | A fast drag with a given velocity |
| `startGesture` | A pointer you control step by step with `moveBy` and `up` |
Use startGesture for multi-step interactions. A pinch is one example, because it needs two pointers.
Common failures
- The tap does nothing and a warning prints. The tap landed on something else, or the widget is off screen. The message says "derived an Offset ... but that would not hit test on the specified widget." Scroll first with
tester.ensureVisibleortester.scrollUntilVisible, or fix the overlap. - A finder matches more than one widget.
tapthrows. Narrow the finder withfind.descendantor aKey. - The state looks unchanged. You forgot
pumpafter the action. - A
Dismissibleerror appears. The removed item must also leave the data source, or the framework reports that the dismissed widget is still in the tree.
You can also test touch target size. IconButton meets the 48 by 48 logical pixel guideline, and a custom tappable widget should as well:
testWidgets('icon button has a large enough touch target', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: IconButton(
tooltip: 'Add to favorites',
icon: const Icon(Icons.favorite_border),
onPressed: () {},
),
),
),
);
final size = tester.getSize(find.byTooltip('Add to favorites'));
expect(size.width, greaterThanOrEqualTo(48));
expect(size.height, greaterThanOrEqualTo(48));
});Exercise
A widget has both onTap and onDoubleTap on one GestureDetector. Your test calls tester.tap once, then pump(), then expects onTap to have run, and it fails. Why, and what is the fix?
Show answer
With onDoubleTap registered, the tap recognizer waits to see whether a second tap follows, so onTap is delayed until the double-tap window closes. A plain pump() advances no time. Call await tester.pump(kDoubleTapTimeout) after the tap, then check the result.
Exercise
Write the two assertions that prove an ElevatedButton is disabled and that tapping it has no effect, given a counter variable named submitted.
Show answer
expect(tester.widget<ElevatedButton>(find.byType(ElevatedButton)).onPressed, isNull); then await tester.tap(find.byType(ElevatedButton)); and expect(submitted, 0);
Exercise
Why does the drag test compare positions with greaterThan instead of checking for exactly Offset(90, 70)?
Show answer
The drag recognizer ignores the first pixels of movement (touch slop) before it starts reporting updates, so the final position can differ from the requested offset. Asserting the direction of movement is robust. Exact values depend on the recognizer's behavior.