Sub topic 1
How scrolling works in Flutter: scrollables and viewports
Prerequisites
This chapter assumes you know Dart lists and closures, can write StatelessWidget and StatefulWidget classes, and understand how Row, Column and Expanded size their children. You should be able to run a Flutter app and use hot reload.
Scrollables and viewports
A scrollable is a widget that moves its content in response to drags and flings. A viewport is the visible window that shows part of that content. ListView and GridView are both scrollables built on a viewport. The viewport decides which children are on screen. The scrollable tracks the scroll offset, which is how far the content has moved from its start.
Your first ListView
ListView with a children list works well for a short list whose items are known in advance.
import 'package:flutter/material.dart';
class ContactsPage extends StatelessWidget {
const ContactsPage({super.key});
@override
Widget build(BuildContext context) {
return ListView(
children: const [
ListTile(title: Text('Ada')),
ListTile(title: Text('Grace')),
ListTile(title: Text('Linus')),
],
);
}
}Direction, padding and reverse
Four properties control the look of a list:
| Property | Effect |
|---|---|
| `scrollDirection` | `Axis.vertical` (default) or `Axis.horizontal` |
| `padding` | Space around the first and last items |
| `reverse` | Starts the content at the end of the viewport |
| `shrinkWrap` | Sizes the list to its content (covered below) |
Fixing unbounded height: Expanded, shrinkWrap and nesting
A viewport needs a finite height or width. A ListView placed directly in a Column has no limit, so Flutter throws "Vertical viewport was given unbounded height". Wrap the list in Expanded to give it the leftover space.
Column(
children: [
const Text('Inbox'),
Expanded(
child: ListView(
children: const [
ListTile(title: Text('Message 1')),
ListTile(title: Text('Message 2')),
],
),
),
],
)ListView.builder for long and dynamic lists
ListView.builder takes an itemCount and an itemBuilder. It calls the builder only for items near the viewport, so it handles long or changing data efficiently.
ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
return ListTile(title: Text(messages[index]));
},
)Exercise
A Column holds a ListView and throws an unbounded height error. Which widget fixes this without changing the list's contents, and why does it work?
Show answer
Wrap the ListView in Expanded. The Column gives Expanded the space left after the other children, so the viewport receives a finite height.