Sub topic 3
Reading and Driving Scroll Position with ScrollController
This chapter assumes you know Dart closures, StatefulWidget with initState and dispose, and ListView.builder. It covers how to read and control scroll position, then how to add loading, physics, refresh, keys, performance, and slivers.
Reading and driving scroll position
A ScrollController gives you access to the scroll position of the scrollable it is attached to. Read controller.position.pixels for the current offset and extentAfter for the distance left before the end. Call jumpTo or animateTo to move the view.
Loading more items near the end
Add a listener in initState and check extentAfter inside it. Dispose the controller in dispose.
class _FeedState extends State<Feed> {
final ScrollController _controller = ScrollController();
final List<int> _items = List<int>.generate(20, (i) => i);
@override
void initState() {
super.initState();
_controller.addListener(_onScroll);
}
void _onScroll() {
if (_controller.position.extentAfter < 300) {
final start = _items.length;
setState(() {
_items.addAll(List<int>.generate(20, (i) => start + i));
});
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListView.builder(
controller: _controller,
itemCount: _items.length,
itemBuilder: (context, index) => ListTile(title: Text('Item ${_items[index]}')),
);
}
}> Warning: Fetching data asynchronously can fire the listener many times while one request is pending. Add a _loading flag and return early while it is set.
Scroll physics and platform behavior
physics controls how the list responds to drags and overscroll. The default follows the platform. Set AlwaysScrollableScrollPhysics when a short list must still scroll, for example so that pull-to-refresh works.
Pull to refresh
RefreshIndicator wraps a scrollable and calls onRefresh, which must return a Future.
RefreshIndicator(
onRefresh: () async {
await Future<void>.delayed(const Duration(seconds: 1));
setState(() => _items.clear());
},
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: _items.length,
itemBuilder: (context, index) => ListTile(title: Text('Item ${_items[index]}')),
),
)Keys and preserving state of list items
When items are reordered or removed, Flutter matches widgets by position unless you give them keys. Use ValueKey with a stable ID so that each row keeps its own state.
| Situation | Key to use |
|---|---|
| Items have a unique ID | `ValueKey(item.id)` |
| Items have no stable ID | `ObjectKey(item)` or a generated key |
Keeping long lists fast
ListView.builder and GridView.builder build only the items near the viewport. Set itemExtent when all rows share one height, because this skips per-item layout measurement.
Mixing lists and grids with CustomScrollView and slivers
CustomScrollView holds slivers, which are scrollable pieces that share one scroll position.
CustomScrollView(
slivers: [
const SliverAppBar(title: Text('Shop'), floating: true),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Featured $index')),
childCount: 3,
),
),
SliverGrid(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
delegate: SliverChildBuilderDelegate(
(context, index) => Card(child: Center(child: Text('Product $index'))),
childCount: 20,
),
),
],
)Exercise
A ListView shows 50 chat messages. Users report that the scroll position jumps when new messages arrive at the top. Which fix addresses the cause?
Show answer
Give each message widget a ValueKey built from its unique message ID, so Flutter matches existing rows to their data instead of their index.