Sub topic 2
Your first ListView
This chapter assumes basic Dart syntax, Flutter widgets, and Row, Column, and Expanded. You should also know how to run an app and use hot reload.
A ListView is a scrollable widget that displays its children along one axis. By default, it scrolls vertically. Flutter gives the ListView a viewport, which is the visible area through which the list moves. Content larger than that area can be reached by scrolling.
Build a list from explicit children
The default ListView constructor takes a fixed list of widgets through its children parameter. This is useful when the list is short and its items are known when the widget is built.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: SettingsPage()));
}
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: ListView(
padding: const EdgeInsets.all(16),
children: const [
ListTile(
leading: Icon(Icons.person),
title: Text('Profile'),
subtitle: Text('Update your account details'),
),
ListTile(
leading: Icon(Icons.notifications),
title: Text('Notifications'),
),
ListTile(
leading: Icon(Icons.lock),
title: Text('Privacy'),
),
],
),
);
}
}ListTile is a ready-made row with common slots such as leading, title, and subtitle. The list can contain any widgets, not only ListTile objects.
The padding adds space inside the scrollable area. Other useful options include:
| Option | Effect |
|---|---|
| `scrollDirection` | Changes scrolling from vertical to horizontal |
| `reverse` | Reverses the scroll direction and item order |
| `physics` | Controls how the list responds to touch and overscroll |
| `shrinkWrap` | Makes the list measure itself from its children |
A list with reverse: true is sometimes useful for chat messages, where newer messages appear at the bottom.
Understand the layout constraint
A scrollable needs a bounded size in the direction in which it scrolls. A ListView placed directly in a Column may produce an “unbounded height” error because the column does not give it a finite height.
Use Expanded when the list should occupy the remaining space:
Column(
children: [
const Text('Inbox'),
Expanded(
child: ListView(
children: const [
ListTile(title: Text('Message one')),
ListTile(title: Text('Message two')),
],
),
),
],
)shrinkWrap: true is another option when the list must size itself to its contents, but it can require more layout work. Avoid using it for a long list unless the surrounding layout requires it.
Exercise
Why can a ListView inside a Column cause an unbounded-height error, and what widget usually fixes it?
Show answer
The Column does not give the vertically scrolling ListView a finite height. Wrap the ListView in Expanded when it should use the remaining space.