Sub topic 1
How Scrolling Works in Flutter: Scrollables and Viewports
Flutter has no single "scroll view" widget that does everything. Scrolling is split across several objects, and ListView and GridView are convenient wrappers around them. Once you know the pieces, errors such as "Vertical viewport was given unbounded height" become predictable instead of mysterious. This chapter builds that mental model. Later chapters cover each constructor in detail.
Prerequisites
This chapter assumes you have:
- Basic Dart syntax, including lists and closures.
- Flutter widget basics:
StatelessWidget,StatefulWidgetandbuild. - Familiarity with
Row,ColumnandExpanded. - A working Flutter project where you can run an app and use hot reload.
The three layers of a scrollable
Every scrolling list or grid in Flutter is made of the same layers.
| Layer | Class | Job |
|---|---|---|
| Gesture and state | `Scrollable` | Listens for drags, flings and mouse wheel events. Owns the `ScrollPosition`. |
| Window | `Viewport` | Clips its content to a fixed-size window and shifts the content by the scroll offset. |
| Content | Slivers such as `SliverList` and `SliverGrid` | Create and lay out the visible children, one scrollable piece at a time. |
A sliver is a portion of a scrollable area. Slivers are not ordinary box widgets. They receive a description of the visible region instead of a width and height, and they report how much scroll space they take up.
ListView and GridView are ScrollView subclasses. A ScrollView builds a Scrollable, puts a Viewport inside it, and fills the viewport with slivers. ListView supplies one SliverList. GridView supplies one SliverGrid. CustomScrollView lets you supply the slivers yourself.
The same list, written out
The following two widgets show the same screen. The first uses the convenient form, and the second shows roughly what it expands to.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Compare())));
class Compare extends StatelessWidget {
const Compare({super.key});
@override
Widget build(BuildContext context) {
// Convenient form.
final simple = ListView.builder(
itemCount: 30,
itemBuilder: (context, index) => ListTile(title: Text('Row $index')),
);
// Roughly equivalent form, with the sliver spelled out.
final explicit = CustomScrollView(
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Row $index')),
childCount: 30,
),
),
],
);
return Row(
children: [
Expanded(child: simple),
const VerticalDivider(width: 1),
Expanded(child: explicit),
],
);
}
}Both columns scroll and look the same. The differences are small. ListView adds options such as itemExtent and applies default padding handling through SliverPadding. The structure is the same.
How constraints flow through a viewport
Flutter's layout rule is that constraints go down and sizes go up. A viewport changes this rule in one specific way.
- The parent gives the viewport constraints. Along the scroll axis, those constraints must be bounded, which means they have a finite maximum height for a vertical list.
- The viewport takes the largest size those constraints allow. It does not shrink to fit its content, because the content can be far larger than the screen.
- The viewport tells its slivers how much space is visible and how far the content has scrolled.
- The slivers build only the children that fall in that window, and report their total scroll extent.
Step 1 explains the most common beginner error. A Column gives its children unbounded height, because a column lets its children be as tall as they want. A ListView inside a Column then receives infinite height and cannot choose a window size. Flutter throws an exception rather than guess.
The fix is to give the list a bounded height, usually by wrapping it in Expanded. The "Fixing unbounded height" chapter covers this in detail, along with shrinkWrap and its costs.
The cross axis is different. A vertical ListView takes its width from its parent and passes that width down to its children as a tight constraint. Each child is therefore as wide as the list.
ScrollPosition and scroll metrics
The Scrollable owns a ScrollPosition. It stores the current offset and decides how the content moves in response to drags and flings. You can read its state through ScrollMetrics, which describes the viewport and the content as numbers in logical pixels.
| Property | Meaning |
|---|---|
| `pixels` | The current scroll offset. |
| `minScrollExtent` | The smallest offset, normally 0. |
| `maxScrollExtent` | The largest offset, which is content length minus viewport length. |
| `viewportDimension` | The size of the visible window along the scroll axis. |
| `extentBefore` | Content hidden before the viewport, equal to `pixels` clamped to the minimum. |
| `extentInside` | Content currently visible. |
| `extentAfter` | Content hidden after the viewport. |
You can observe these values without any controller by listening for notifications. Scroll notifications bubble up the widget tree from the Scrollable, so a NotificationListener above the list receives them.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: MetricsDemo())));
class MetricsDemo extends StatelessWidget {
const MetricsDemo({super.key});
@override
Widget build(BuildContext context) {
return NotificationListener<ScrollNotification>(
onNotification: (notification) {
final m = notification.metrics;
debugPrint(
'pixels=${m.pixels.toStringAsFixed(0)} '
'before=${m.extentBefore.toStringAsFixed(0)} '
'inside=${m.extentInside.toStringAsFixed(0)} '
'after=${m.extentAfter.toStringAsFixed(0)}',
);
return false; // Let the notification keep bubbling.
},
child: ListView.builder(
itemCount: 50,
itemBuilder: (context, index) => ListTile(title: Text('Row $index')),
),
);
}
}Run the app and drag the list. The console prints a line for each scroll update. extentBefore + extentInside + extentAfter stays equal to the full content length as long as the list does not change. If you build the list lazily, this total is an estimate until you reach the end. The estimate is why a scrollbar thumb can change size slightly as you scroll.
A ScrollController is the other way to reach the position. You pass it to the scrollable's controller parameter, and it attaches to the ScrollPosition. Use it when you need to read the offset from outside, or to move the list with jumpTo and animateTo. The "ScrollController" chapter covers it.
Lazy building
A Viewport shows a small slice of a possibly huge list. Its slivers take advantage of that. A SliverList built with SliverChildBuilderDelegate calls your builder only for indexes near the visible window. Items that scroll far out of view are disposed of, and their State objects are lost unless you take extra steps.
The result is that a list of 100,000 rows costs about as much as a list of 20 rows, because only about 20 are alive at once. A list built from an explicit children list is different. You have already created every child widget before the sliver sees them. Flutter still lays out only the visible ones, but all the widget objects exist in memory.
Platform behavior and the primary controller
Two details often surprise people.
Scrollablepicks default physics from the platform. Android gets clamping physics, which stops at the edge with a glow or stretch effect. iOS and macOS get bouncing physics. Flutter reads these defaults from the app'sScrollBehavior.- A vertical scroll view that has no explicit
controllermay use thePrimaryScrollControlleron mobile platforms. This is how tapping the status bar on iOS scrolls the main list to the top. If two vertical lists on one screen both claim the primary controller, Flutter reports that a controller is attached to more than one position.
Common mistakes
- Putting a vertical list directly inside another vertical scrollable. The inner list gets unbounded height. Use
Expanded, a fixedSizedBox, or restructure withCustomScrollView. - Expecting state to persist off-screen. Items outside the viewport are disposed. Keep important state in a parent object or use keep-alive mechanisms, which a later chapter covers.
- Reading
controller.positionbefore attachment. A controller only has a position once the scrollable has been built. Read it in a callback after the first frame, or checkcontroller.hasClients. - Forgetting to dispose a controller. A
ScrollControlleryou create ininitStatemust be disposed indispose.
Exercise
A developer writes Column(children: [Text('Title'), ListView.builder(itemCount: 10, itemBuilder: (c, i) => ListTile(title: Text('$i')))]) and gets an unbounded-height error. Using the viewport model, explain why it happens and give one fix.
Show answer
A Column passes unbounded height to its children. A ListView creates a Viewport that sizes itself to the largest height its constraints allow, so with infinite height it cannot choose a finite window size and Flutter throws. The fix is to give the list a bounded height. The usual choice is to wrap the ListView.builder in Expanded, so it takes the space the Column has left after the Text.
Exercise
In the NotificationListener example, the list has 50 rows of 56 pixels each and the viewport is 600 pixels tall. What are maxScrollExtent and extentAfter when pixels is 1000?
Show answer
The content length is 50 × 56 = 2800 pixels. maxScrollExtent is 2800 − 600 = 2200. extentAfter is the content left past the viewport: 2800 − (1000 + 600) = 1200, which equals maxScrollExtent minus pixels (2200 − 1000).