Sub topic 2
Your first ListView
This chapter covers the default ListView constructor, which takes an explicit list of children. It assumes you can write basic Dart (lists, closures), know StatelessWidget and StatefulWidget, are comfortable with Row, Column and Expanded, and can run an app with hot reload.
What ListView gives you
A ListView is a scrollable list of widgets along one axis, vertical by default. It combines three pieces that you would otherwise assemble yourself:
- A
Scrollable, which listens for drag and fling gestures and tracks the scroll offset. - A
Viewport, which is the window onto content that may be taller than the screen. - A
SliverList, which lays the children out one after another inside that window.
You rarely touch these parts directly. Knowing they exist explains later behavior, such as why a ListView needs a bounded height and why you can swap it for a CustomScrollView.
The default constructor
The default constructor takes a children list. This is the right choice when you know the items at coding time and there are only a few of them: a settings screen, a menu, or a form.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Account')),
body: ListView(
padding: const EdgeInsets.all(16),
children: const [
ListTile(title: Text('Profile')),
ListTile(title: Text('Settings')),
ListTile(title: Text('About')),
],
),
),
);
}
}Four details in this example:
ListTileis a Material widget that arranges a leading icon, a title, a subtitle and a trailing widget in a standard row. It needs aMaterialancestor, whichScaffoldprovides.- The
childrenlist and every tile in it areconst. Flutter can reuse these widget instances on every rebuild instead of allocating new ones. paddinginsets the content inside the scroll area. The first item starts 16 pixels from the top edge, and when you scroll it still moves out of view normally. Padding on a surroundingPaddingwidget would instead clip items at the padded edge.- The screen shows no scrollbar or other cue. The list scrolls only when the content is taller than the viewport.
What is built, and when
A common belief is that the default constructor builds everything at once while ListView.builder builds lazily. The real difference is narrower.
With ListView(children: [...]), you create all the child widgets yourself, up front, whenever your build method runs. A widget is a lightweight description, so this is cheap for a handful of items. However, Flutter still creates the elements and render objects lazily. Only the children inside or near the viewport get laid out and painted.
The cost of the default constructor is therefore the work you do to produce the widget list. Constructing 10,000 ListTile objects on every rebuild wastes time and memory even though most never reach the screen. ListView.builder, covered in a later chapter, avoids this by calling your function only for the indexes that need to be shown.
Generating children from data
You can build the children list from a collection with map. This works well for small data sets that are not worth a builder.
import 'package:flutter/material.dart';
class TagList extends StatelessWidget {
const TagList({super.key, required this.tags});
final List<String> tags;
@override
Widget build(BuildContext context) {
return ListView(
children: [
const ListTile(
title: Text('Tags', style: TextStyle(fontWeight: FontWeight.bold)),
),
...tags.map(
(tag) => ListTile(
leading: const Icon(Icons.label),
title: Text(tag),
),
),
],
);
}
}The spread operator ... inserts each item of the mapped iterable into the surrounding list literal. Without it you would pass an Iterable as a single element, and the code would not compile. The const is gone from the outer list because tags is only known at runtime. Keep const on the fixed header tile and on the inner Icon.
You can mix fixed and generated children freely, which is a real advantage of the default constructor. A builder gives each index a single widget builder, so a header requires special handling there.
Making tiles respond to taps
ListTile exposes onTap and onLongPress. Because a ListView is a normal widget, state lives in a StatefulWidget above it, and setState rebuilds the children.
import 'package:flutter/material.dart';
class ChoiceList extends StatefulWidget {
const ChoiceList({super.key});
@override
State<ChoiceList> createState() => _ChoiceListState();
}
class _ChoiceListState extends State<ChoiceList> {
static const _options = ['Small', 'Medium', 'Large'];
String _selected = 'Medium';
@override
Widget build(BuildContext context) {
return ListView(
children: [
for (final option in _options)
ListTile(
title: Text(option),
trailing: option == _selected ? const Icon(Icons.check) : null,
onTap: () => setState(() => _selected = option),
),
],
);
}
}This uses collection for inside the list literal, an alternative to map and spread that many people find easier to read. Tapping a tile changes _selected, setState triggers build, and the list produces a new set of tiles with the check mark on the chosen one. The scroll position is preserved across this rebuild because the ListView's scroll state lives in a State object that Flutter keeps, not in your widget list.
Common errors
- Too many children in the default constructor. A list of thousands of items works but wastes work on each rebuild. Switch to
ListView.builder. - Passing a list inside a list. Writing
children: [items.map(...)]orchildren: [[a, b]]fails because the element is not aWidget. Spread the iterable with...or use collectionfor. - Forgetting
.toList()when not using a list literal.childrenexpects aList<Widget>. If you writechildren: items.map((i) => Text(i))without a surrounding[...]and spread, you pass anIterable<Text>and get a type error. Add.toList(), or use the spread form shown above. - Missing Material ancestor.
ListTileoutside aScaffold,CardorMaterialthrows "No Material widget found". Wrap it or place the list inside aScaffold. - Placing a ListView directly in a Column. The app throws a "Vertical viewport was given unbounded height" error, because a
ListViewwants as much height as it can get and aColumnoffers unlimited height. The usual fix, wrapping the list inExpanded, gets its own chapter.
Checking your understanding
Try to predict the behavior before you run it. In the ChoiceList example, scroll partway down a long version of the list, tap a tile, and see whether the list jumps to the top. It does not, because the scroll offset is kept by the scrollable's state.
Exercise
You write ListView(children: items.map((i) => ListTile(title: Text(i)))) where items is a List<String>, and the compiler reports a type error. What is wrong, and give two ways to fix it.
Show answer
The map call returns an Iterable<ListTile>, but children requires a List<Widget>. Fix 1: add .toList() after map(...). Fix 2: put the map inside a list literal and spread it, as in children: [...items.map((i) => ListTile(title: Text(i)))]. Collection for, as in children: [for (final i in items) ListTile(title: Text(i))], also works.
Exercise
A screen shows 5,000 database rows using the default ListView constructor. Flutter only paints the visible rows, so why is this still a poor choice?
Show answer
Flutter creates elements and render objects lazily, but the default constructor needs you to create all 5,000 widget objects each time build runs. That work and memory are spent for rows that are never shown. ListView.builder creates widgets only for the indexes near the viewport.