Sub topic 8
Scrolling lists and dragging
This chapter covers how to test content that is not on screen yet. It assumes you can write a basic testWidgets test with pumpWidget, use find.text and find.byType, and know the difference between pump and pumpAndSettle.
Why scrolling needs its own techniques
A ListView.builder builds only the items near the viewport, plus a small buffer called the cache extent. In a test, an item far down the list does not exist in the widget tree. find.text('Item 80') finds nothing, and findsOneWidget fails, even though the app would show the item once a user scrolled.
The test therefore has to do what the user does: scroll until the widget is built. WidgetTester offers four tools for this.
| Method | What it does | Use it when |
|---|---|---|
| `scrollUntilVisible` | Repeatedly drags a scrollable until a finder matches | You know the target item, not its position |
| `drag` | Moves a pointer by an exact offset | You want a precise scroll distance, swipe, or pull |
| `fling` | Drags with a velocity, so the scroll keeps going | You want to test momentum or overscroll |
| `ensureVisible` | Scrolls ancestors so an already built widget is on screen | The widget exists but is partly or fully offscreen |
scrollUntilVisible
scrollUntilVisible is the simplest option for lazily built lists.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
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);
});
}The second argument, delta, is the distance in logical pixels to scroll on each attempt. A positive value on a vertical list scrolls down, so content moves up. Each iteration the tester checks the finder, drags by delta if there is no match, and pumps a short duration. A single-line ListTile is 56 pixels tall, so Item 80 sits about 4,480 pixels down. With delta 500, the loop needs roughly nine iterations.
The method accepts three named parameters worth knowing:
scrollableis a finder for the scrollable to drag. It defaults to theScrollablein the tree, so pass it explicitly when the screen has more than one scrollable. Both a nested list and aTextFieldcontain aScrollable.maxScrollsdefaults to 50. If the target has not appeared after that many attempts, the call fails with an error instead of looping forever.durationis the time pumped after each drag. The default is short, which is enough for non-animated lists.
await tester.scrollUntilVisible(
find.text('Item 80'),
500,
scrollable: find.byKey(const Key('main-list')),
maxScrolls: 20,
);To scroll up, use a negative delta. To scroll a horizontal list, the same rule applies along the horizontal axis: a positive value moves toward the end of the list.
The loop is easy to model, and the model explains most failures:
Two mistakes cause most of those errors. The first is a delta with the wrong sign, so the list scrolls away from the target. The second is a delta so small that maxScrolls runs out before the target is reached. A delta larger than the viewport can also skip past an item without it ever being built at the right moment. Keep delta at or below the viewport height. The default test surface is 800 by 600 logical pixels.
drag and fling
drag simulates a finger touching a widget and moving by an Offset. The offset points in the direction the finger travels. To scroll a vertical list down, drag upward with a negative dy.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
Widget buildList() {
return MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: 100,
itemBuilder: (context, i) => ListTile(title: Text('Item $i')),
),
),
);
}
double scrollOffset(WidgetTester tester) {
final state = tester.state<ScrollableState>(find.byType(Scrollable));
return state.position.pixels;
}
void main() {
testWidgets('drag moves the list by roughly the offset', (tester) async {
await tester.pumpWidget(buildList());
expect(find.text('Item 0'), findsOneWidget);
await tester.drag(find.byType(ListView), const Offset(0, -600));
await tester.pump();
expect(find.text('Item 0'), findsNothing);
expect(find.text('Item 15'), findsOneWidget);
expect(scrollOffset(tester), greaterThan(500));
});
testWidgets('fling keeps scrolling after the pointer lifts', (tester) async {
await tester.pumpWidget(buildList());
await tester.fling(find.byType(ListView), const Offset(0, -500), 1000);
await tester.pumpAndSettle();
expect(scrollOffset(tester), greaterThan(500));
});
}Points to note in this example:
dragis followed bypump(). The drag changes the scroll position, and the new frame builds the newly visible items.- The test checks
Item 15and agreaterThanbound, not an exact pixel count. Touch slop, the small distance a pointer must move before a drag is recognised, can make the actual scroll differ slightly from the offset you asked for. Avoid asserting exact positions after adrag. flingtakes a third argument, the speed in pixels per second. The list keeps moving under a scroll simulation after the pointer lifts, so usepumpAndSettleto let it come to rest.tester.state<ScrollableState>reads the real scroll position. The chapter on inspecting widgets and state covers this pattern in more detail.
Dragging for other gestures
drag is not limited to lists. Any gesture that is a pointer moving across a widget can be driven with it:
- A
Dismissibleswipe:await tester.drag(find.text('Item 3'), const Offset(500, 0));thenawait tester.pumpAndSettle();. The dismiss animation must finish before the item leaves the tree. - A
PageViewswipe: drag by a negative horizontal offset, thenpumpAndSettleso the page snaps into place. - Pull to refresh: drag a scrollable down by a few hundred pixels, then pump with explicit durations to step through the indicator's animation.
For gestures like these, the offset must be large enough to cross the widget's threshold. A Dismissible needs to be dragged past its dismiss threshold, which is 40 percent of its width by default. If the widget snaps back, the drag was too short.
Built is not the same as visible
Because of the cache extent, a finder can match a widget that is built but outside the visible area. Two consequences follow.
First, findsOneWidget does not prove an item is visible. If you need that, compare the item's rectangle with the viewport, or scroll to it and then assert on content that is only possible when it is on screen.
Second, tapping a built but offscreen widget produces a warning like "A call to tap() with finder ... derived an Offset that would not hit test on the specified widget." The tap goes nowhere, and the test may fail later for an unrelated reason. Fix it by calling ensureVisible first:
await tester.ensureVisible(find.text('Item 12'));
await tester.pump();
await tester.tap(find.text('Item 12'));
await tester.pump();ensureVisible only works on a widget that already exists. If the item has not been built yet, use scrollUntilVisible first.
Common errors
- The target never appears. Check the
deltasign, themaxScrollslimit, and whetherscrollablepoints at the right list. A nested list can swallow the drag. - The list did not move. Make sure the finder given to
dragis the scrollable or one of its descendants. Dragging a widget outside the list does nothing. - The assertion runs too early. After
dragorfling, callpumporpumpAndSettle. Without a frame, the tree still shows the old items. pumpAndSettletimes out. An infinite animation, such as a spinner at the end of a paginated list, keeps scheduling frames. Usepumpwith a fixedDurationinstead.- Item heights surprise you. The default test surface is small. If a screen layout assumes a phone, set a size with
tester.view.physicalSizeand reset it withaddTearDown(tester.view.reset).
Exercise
A test calls await tester.scrollUntilVisible(find.text('Item 80'), -500); on a 100-item vertical ListView.builder that starts at the top, and it fails with an error after many attempts. What is wrong, and how do you fix it?
Show answer
A negative delta scrolls toward the top of the list, which is already at its start, so Item 80 never gets built. The loop ends when it reaches maxScrolls (50 by default) and the call throws. Use a positive delta, such as 500, to scroll down. Keep it no larger than the viewport height so the loop does not skip past the target.
Exercise
After await tester.drag(find.byType(ListView), const Offset(0, -600)); an assertion that find.text('Item 15') finds one widget fails, but the app clearly shows Item 15 when scrolled by hand. Name two likely causes.
Show answer
Either the test did not call pump() after the drag, so the tree was not rebuilt with the newly visible items, or the finder passed to drag did not match the scrollable, so the list never moved. Adding await tester.pump(); after the drag and checking the finder usually fixes it.