Sub topic 5
ListView.builder for long and dynamic lists
This chapter assumes you know Dart lists and closures, StatefulWidget and setState, and the basic ListView(children: [...]) constructor from earlier chapters. You should also be able to run a Flutter app and use hot reload.
Why the default constructor does not scale
ListView(children: [...]) needs every child widget to exist before the list is shown. For three settings rows, that is fine. For 10,000 messages, you would create 10,000 widgets up front, even though the screen shows about a dozen.
ListView.builder takes a different approach. You describe how to build the item at a given index, and Flutter calls that function only for the items it needs.
ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
return ListTile(title: Text(messages[index]));
},
)Two parameters matter most:
itemCountis the number of items. Flutter callsitemBuilderonly with indexes from 0 toitemCount - 1.itemBuilderis a function(BuildContext context, int index) => Widget. It must return a widget for every valid index.
What Flutter does with your builder
The list sits inside a viewport, the visible window onto the scrolling content. As the user scrolls, the list asks itemBuilder for items that are inside the viewport or within a small buffer beyond it. This buffer is the cacheExtent, 250 logical pixels by default. When an item scrolls far enough out of range, Flutter discards its widget and element and frees its state.
Three consequences follow from this:
itemBuildercan run many times for the same index. It runs again when the item scrolls back in, and again whenever the list rebuilds. Keep it fast and free of side effects.- Item state is temporary. A checkbox's
Stateinside an item is lost when the item scrolls away. Keep the real data in your model, not in the item widget. Later chapters on keys and state cover the alternatives. - The list does not know its content height in advance. Flutter estimates the total extent from the items it has measured. That is why scrollbar thumbs can shift slightly while you scroll through items of varying height.
A runnable example with a dynamic list
The following app has 1,000 tasks. You can add a task with the floating button and swipe a task away to remove it. The debugPrint call lets you see in the console which indexes are built.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: TaskList()));
class TaskList extends StatefulWidget {
const TaskList({super.key});
@override
State<TaskList> createState() => _TaskListState();
}
class _TaskListState extends State<TaskList> {
int _nextId = 1000;
final List<String> _tasks = List<String>.generate(1000, (i) => 'Task $i');
void _add() {
setState(() {
_tasks.insert(0, 'Task ${_nextId++}');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('${_tasks.length} tasks')),
floatingActionButton: FloatingActionButton(
onPressed: _add,
child: const Icon(Icons.add),
),
body: ListView.builder(
itemCount: _tasks.length,
itemBuilder: (context, index) {
debugPrint('build item $index');
final task = _tasks[index];
return Dismissible(
key: ValueKey(task),
onDismissed: (_) {
setState(() => _tasks.remove(task));
},
child: ListTile(
leading: const Icon(Icons.check_circle_outline),
title: Text(task),
),
);
},
),
);
}
}Run it and watch the console. At startup you will see roughly a dozen build item lines, not 1,000. Scroll down and new indexes appear in the log. Scroll back up and the earlier indexes are built again.
A few details in this code are worth noting:
- The list data lives in the
Stateobject, and every change goes throughsetState. Changing_taskswithoutsetStateleaves the screen out of date. Dismissiblerequires akey. The key identifies the task, not its position, so removing one task does not confuse the others. This is why the code usesValueKey(task)and not the index._nextIdis a separate counter so new tasks never reuse a name. Using_tasks.lengthwould produce duplicate keys after a removal.
Common errors
RangeError when the count is wrong
itemCount must match the data you index into. The classic mistake is a stale or oversized count:
ListView.builder(
itemCount: 10, // the list may hold fewer than 10 items
itemBuilder: (context, index) => Text(items[index]), // RangeError
)Use items.length, and read the length from the same list that itemBuilder indexes.
Leaving out itemCount
If you omit itemCount, the list is treated as infinite. Flutter keeps calling itemBuilder with larger indexes as the user scrolls, and your builder runs past the end of the data. To handle this deliberately, return null from itemBuilder to say that no more items exist:
ListView.builder(
itemBuilder: (context, index) {
if (index >= items.length) return null; // ends the list
return ListTile(title: Text(items[index]));
},
)Setting itemCount is clearer and gives the scrollbar a correct total. Use the null form only when the count is unknown.
Unbounded height
ListView.builder has the same layout rule as every ListView. Inside a Column it needs a bounded height, so wrap it in Expanded. Using shrinkWrap: true on a builder list forces Flutter to measure all items, which removes the laziness this chapter is about.
Mutating a list inside itemBuilder
itemBuilder runs during the build phase. Calling setState, or changing the data it reads, from inside the builder triggers errors or inconsistent output. Change data in event handlers (onPressed, onDismissed) and let the rebuild read it.
Expensive work in the builder
Because the builder can run repeatedly for the same index, avoid sorting, filtering, parsing, or network calls inside it. Prepare the data once, in initState or in response to an event, and have the builder only read from it.
Helping Flutter measure items
By default, Flutter lays out each visible child to learn its size. If all items have the same main-axis size, tell the list. This saves layout work and makes scroll positions exact.
ListView.builder(
itemExtent: 72, // every item is 72 logical pixels tall
itemCount: 5000,
itemBuilder: (context, index) => ListTile(title: Text('Row $index')),
)When the items are the same size but you do not want to hard-code the number, prototypeItem takes a sample widget and measures it once.
| Parameter | What you provide | Use when |
|---|---|---|
| `itemExtent` | A fixed size in logical pixels | Every item has a known, identical size |
| `prototypeItem` | A widget with the same size as the items | Items are identical in size, but the size depends on text scale or theme |
| Neither | Nothing | Item sizes vary |
Do not set either option when items vary in size. Content that does not fit the forced size will be clipped or leave gaps.
Choosing a constructor
- Use
ListView(children: [...])for a short, fixed list such as a settings page. - Use
ListView.builderwhen the list is long, comes from data, or changes at runtime. - Use
ListView.separated, covered in the next chapter, when you want dividers or gaps between items.
If you are unsure, prefer the builder. It behaves well for a list of five items and for a list of five thousand.
Exercise
A screen shows a ListView.builder with itemCount: users.length. After the user deletes the last user, the app throws a RangeError for index 0. The delete handler calls users.clear() without setState. Which two facts explain the error and its fix?
Show answer
The builder still holds the old itemCount, because without setState the list is not rebuilt and the screen keeps asking for indexes that no longer exist in users. A later build with a stale count then indexes an empty list. The fix is to change the data inside setState(() => users.clear()), so the rebuild reads the new users.length (now 0) and itemBuilder is never called.
Exercise
You have a ListView.builder of 50,000 rows, and each row is exactly 56 logical pixels tall. Which parameter can make layout cheaper, and why should you avoid adding shrinkWrap: true?
Show answer
Set itemExtent: 56, which lets Flutter skip measuring each child and compute scroll positions directly. shrinkWrap: true makes the list measure all 50,000 items to find its own height, which removes the benefit of lazy building.