Sub topic 10
Reading and driving scroll position with ScrollController
This chapter assumes you can build a ListView or GridView, write a StatefulWidget with initState and dispose, and read a closure. You will learn how a ScrollController reports where a scrollable is and how it moves the scrollable. You will also learn which errors come up when you use one.
What a ScrollController does
A scrollable widget such as ListView or GridView keeps its own scroll state internally. By default you cannot see that state or change it. A ScrollController is an object you create and pass to the scrollable through its controller parameter. After that, the controller can:
- Read the current position, by reading
offsetorposition. - Notify you when the position changes, because the controller is a
Listenable. - Move the scrollable, with
jumpToandanimateTo. - Set the starting position, with the
initialScrollOffsetconstructor argument.
The controller is a long-lived object. Create it once in a State and dispose of it when the State is disposed.
Reading the position
The controller exposes the live ScrollPosition as controller.position. Most of the values you need are on it.
| Property | Meaning |
|---|---|
| `pixels` (same as `controller.offset`) | Distance scrolled from the start, in logical pixels |
| `minScrollExtent` | Lowest offset, usually 0 |
| `maxScrollExtent` | Highest offset the scrollable currently knows about |
| `viewportDimension` | Size of the visible window along the scroll axis |
| `extentBefore` | Content hidden before the viewport |
| `extentInside` | Content currently inside the viewport |
| `extentAfter` | Content hidden after the viewport |
extentAfter is the easiest way to ask "how close am I to the end?". It does not depend on direction or on reverse.
A back-to-top button
This page shows a floating button once the user has scrolled more than 400 pixels. Pressing it scrolls back to the top.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: BackToTopPage()));
class BackToTopPage extends StatefulWidget {
const BackToTopPage({super.key});
@override
State<BackToTopPage> createState() => _BackToTopPageState();
}
class _BackToTopPageState extends State<BackToTopPage> {
final ScrollController _controller = ScrollController();
bool _showButton = false;
@override
void initState() {
super.initState();
_controller.addListener(_onScroll);
}
void _onScroll() {
final show = _controller.offset > 400;
if (show != _showButton) {
setState(() => _showButton = show);
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Back to top')),
body: ListView.builder(
controller: _controller,
itemCount: 100,
itemBuilder: (context, index) => ListTile(title: Text('Row $index')),
),
floatingActionButton: _showButton
? FloatingActionButton(
onPressed: () => _controller.animateTo(
0,
duration: const Duration(milliseconds: 400),
curve: Curves.easeOut,
),
child: const Icon(Icons.arrow_upward),
)
: null,
);
}
}The listener runs on every scroll frame. It calls setState only when the boolean changes. Calling setState on every frame would rebuild the whole page 60 or more times per second for no visible gain.
Moving the scrollable
There are two methods for moving, and they differ in one way.
jumpTo(double offset)changes the position immediately and returns nothing. Any ongoing scroll animation or fling stops.animateTo(double offset, {required Duration duration, required Curve curve})returns aFuture<void>that completes when the animation ends. Await it if you need to run code afterwards.
Both clamp nothing for you in the same way on every platform. On platforms with bouncing physics, an offset past the extent can be reached temporarily. Clamp targets yourself when you compute them.
Scrolling to an index
Flutter's lazy lists do not know the position of an item that has not been built. The controller therefore has no scrollToIndex. When every item has the same height, you can compute the offset. Setting itemExtent on the ListView fixes that height and also makes layout cheaper.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: JumpToRowPage()));
class JumpToRowPage extends StatefulWidget {
const JumpToRowPage({super.key});
@override
State<JumpToRowPage> createState() => _JumpToRowPageState();
}
class _JumpToRowPageState extends State<JumpToRowPage> {
static const double _rowHeight = 56;
final ScrollController _controller = ScrollController();
Future<void> _scrollToIndex(int index) async {
if (!_controller.hasClients) return;
final target = (index * _rowHeight)
.clamp(0.0, _controller.position.maxScrollExtent)
.toDouble();
await _controller.animateTo(
target,
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Jump to row'),
actions: [
TextButton(
onPressed: () => _scrollToIndex(60),
child: const Text('Row 60'),
),
],
),
body: ListView.builder(
controller: _controller,
itemExtent: _rowHeight,
itemCount: 100,
itemBuilder: (context, index) => ListTile(title: Text('Row $index')),
),
);
}
}If row heights vary, this arithmetic is wrong. Other options exist, such as Scrollable.ensureVisible on an item that is already built, or a package that tracks item positions. This tutorial does not cover them.
Starting at a given offset
Pass initialScrollOffset to the constructor to open the list partway down:
final ScrollController controller = ScrollController(initialScrollOffset: 560);If you need to start at the bottom, as in a chat view, reverse: true on the ListView is usually simpler than computing maxScrollExtent. See the direction chapter for that parameter.
Common errors
Reading the controller before it is attached
A controller is attached to a scrollable only after that scrollable is built. These members throw if no scrollable is attached:
controller.positioncontroller.offsetcontroller.jumpTocontroller.animateTo
A typical message is ScrollController not attached to any scroll views. This happens when you call animateTo in initState, or after the scrollable has been removed from the tree. Guard with hasClients:
if (_controller.hasClients) {
_controller.jumpTo(0);
}If you really need to move the list right after the first build, defer the call until the frame is finished:
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_controller.hasClients) {
_controller.jumpTo(_controller.position.maxScrollExtent);
}
});
}Sharing one controller between two scrollables
One controller can be attached to several scrollables, but position and offset then fail with an assertion saying the controller is attached to multiple scroll views. Give each scrollable its own controller. If two lists must scroll together, synchronize them in a listener and keep the code that handles feedback loops explicit.
Creating the controller inside build
@override
Widget build(BuildContext context) {
final controller = ScrollController(); // wrong
return ListView(controller: controller, children: const []);
}Each rebuild creates a new controller. The old one is never disposed, and the scroll position resets because the new controller starts from zero. Create the controller in a State field and dispose of it.
Forgetting to dispose
A controller that is never disposed leaks its listeners and its position. Always call dispose() in the State's dispose, before super.dispose().
Trusting maxScrollExtent on a lazy list
A ListView.builder with itemCount set knows how many items there are but not their heights. It estimates the total extent from the items built so far. When you animateTo(maxScrollExtent), the list may land short, because new items are measured during the scroll and the maximum grows. Repeating the call after the animation, or using itemExtent, reduces this problem.
Listening without a controller
A controller is not the only way to watch scrolling. A NotificationListener<ScrollNotification> placed above the scrollable receives start, update and end events from any scrollable below it. This works when you cannot or do not want to own the controller, for example when the scrollable is created inside another widget. Use a controller when you also need to drive the position.
Putting it together
A good working pattern has four parts.
- Hold one
ScrollControlleras a final field of aState. - Register a listener in
initStatethat readsoffsetorextentAfterand callssetStateonly on change. - Guard every
jumpTo,animateToandpositionaccess withhasClients. - Dispose of the controller in
dispose.
The next chapter builds on this pattern to load more items as the user nears the end of a list.
Exercise
A page calls _controller.animateTo(0, duration: const Duration(milliseconds: 300), curve: Curves.easeOut) inside initState and throws "ScrollController not attached to any scroll views". Why does it throw, and how do you fix it?
Show answer
In initState the ListView has not been built yet, so the controller has no attached position. Defer the call with WidgetsBinding.instance.addPostFrameCallback, and check _controller.hasClients inside the callback before calling animateTo. If the goal is only to start at a given offset, pass initialScrollOffset to the ScrollController constructor instead.
Exercise
You show a "scroll to top" button when the user has scrolled more than 400 pixels. Your listener calls setState(() => _showButton = _controller.offset > 400) on every notification, and the list stutters. What change keeps the behavior and avoids the stutter?
Show answer
Compute the new boolean first and call setState only when it differs from the stored _showButton. The listener still runs every frame, but the page rebuilds only when the button needs to appear or disappear.