Sub topic 10
Build long lists lazily and keep item identity stable
Long lists are where a rebuild problem turns into a frame-time problem. A list with thousands of rows can cost nothing if Flutter builds only the visible rows. The same list can freeze the UI if every row is built eagerly, or if rows lose their identity when the data changes. This chapter covers both halves: lazy construction and stable identity.
This chapter assumes you can write StatelessWidget and StatefulWidget classes and use setState. It also assumes you know that Flutter decides whether to reuse an element by comparing a widget's type and key. The earlier chapters on rebuild scope and const widgets apply here too.
Eager lists build everything
The default ListView constructor takes a ready-made list of children. Every child widget is created, and every child is mounted and laid out, before the user scrolls.
// Eager: creates all 10,000 tiles up front.
ListView(
children: [
for (final item in items) ProductTile(product: item),
],
)Each setState on the parent runs this whole expression again. That means 10,000 constructor calls, plus a diff of 10,000 children, even though about 12 are on screen.
SingleChildScrollView with a Column has the same problem. It is fine for a short form, but it should not hold a long, data-driven list.
Lazy lists build what is near the viewport
ListView.builder takes an itemCount and an itemBuilder callback. Flutter calls itemBuilder only for indexes that are visible or inside the cache area just beyond the viewport.
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return ProductTile(key: ValueKey(item.id), product: item);
},
)Three details matter in practice:
- The cache area.
cacheExtentis how far beyond the viewport Flutter builds rows. The default for aListViewis 250 logical pixels. Raising it builds more rows ahead of time and smooths fast flings, but it costs memory and build work. - Disposal. A row that scrolls well away is disposed, and so is its
State. Scroll back andinitStateruns again. Do not keep data that must survive only in a tile'sState. - Rebuild cost. When the parent rebuilds, only the mounted rows (roughly a screenful) are rebuilt, not the whole data set.
Help layout with a known extent
If every row has the same height, set itemExtent. If rows share a height that you do not know in advance, use prototypeItem. Either lets the sliver skip measuring each child to compute scroll offsets, and it makes jumps to a given index cheap.
ListView.builder(
itemExtent: 72,
itemCount: items.length,
itemBuilder: (context, index) => ProductTile(product: items[index]),
)Do not set itemExtent if rows have different heights. The rows will be forced to one height and content will be clipped.
Why item identity matters
When a parent rebuilds, Flutter walks the old element tree and the new widget list. For each slot it asks Widget.canUpdate: do the old and new widgets have the same runtimeType and the same key? If yes, the element and its State are kept and updated. If no, the element is discarded and a new one is created.
Without keys, identity is positional. Suppose a list of stateful tiles has a checkbox in each tile's State. You reverse the data. The tile at position 0 is still a ProductTile, so Flutter keeps its element and State. The checkbox stays ticked at position 0, but the data behind it is now a different product. This is the classic "wrong row is selected after sorting" bug.
A key ties the State to the data, not to the position. ValueKey(item.id) says "this tile belongs to product 42, wherever it appears".
A runnable reorder demo
This app has a thousand rows, each with its own selection state. Select a few rows near the top, then press the reverse button.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ReorderDemo()));
class Product {
const Product(this.id, this.name);
final int id;
final String name;
}
class ReorderDemo extends StatefulWidget {
const ReorderDemo({super.key});
@override
State<ReorderDemo> createState() => _ReorderDemoState();
}
class _ReorderDemoState extends State<ReorderDemo> {
List<Product> _items =
List.generate(1000, (i) => Product(i, 'Product $i'));
late Map<int, int> _indexById = _buildIndex();
Map<int, int> _buildIndex() => {
for (var i = 0; i < _items.length; i++) _items[i].id: i,
};
void _reverse() {
setState(() {
_items = _items.reversed.toList();
_indexById = _buildIndex();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Reorder demo'),
actions: [
IconButton(
icon: const Icon(Icons.swap_vert),
onPressed: _reverse,
),
],
),
body: ListView.builder(
itemCount: _items.length,
findChildIndexCallback: (key) {
if (key is ValueKey<int>) return _indexById[key.value];
return null;
},
itemBuilder: (context, index) {
final item = _items[index];
return ProductTile(key: ValueKey(item.id), product: item);
},
),
);
}
}
class ProductTile extends StatefulWidget {
const ProductTile({super.key, required this.product});
final Product product;
@override
State<ProductTile> createState() => _ProductTileState();
}
class _ProductTileState extends State<ProductTile> {
bool _selected = false;
@override
Widget build(BuildContext context) {
return CheckboxListTile(
title: Text(widget.product.name),
value: _selected,
onChanged: (value) => setState(() => _selected = value ?? false),
);
}
}With the key, the ticked rows follow their products to the bottom of the list. Remove key: ValueKey(item.id) and the ticks stay at the top, attached to different products.
What findChildIndexCallback does
In a builder list, children are tracked by index. When the order changes, Flutter needs to know where an existing keyed child went. findChildIndexCallback answers that question: given a key, return the child's new index, or null if unknown. If you omit it, a keyed child may not be matched to its existing render object after a reorder, and its state can be lost. The callback may be called many times per rebuild, so use a map lookup. A indexWhere scan over 1,000 items on every call would turn a cheap lookup into quadratic work.
Choosing keys
| Choice | Behavior | Verdict |
|---|---|---|
| No key | State follows position | Fine for stateless tiles and lists that never reorder |
| `ValueKey(item.id)` | State follows the data's stable id | Default choice |
| `ValueKey(index)` | Same as no key, with extra noise | Avoid. It is the position again |
| `ObjectKey(item)` | Identity by object equality or identity | Use only when no id exists and the object is stable |
| `UniqueKey()` created in `build` | New key every build, so every tile is rebuilt from scratch | Never in `build` |
| `GlobalKey` per row | Moves state across parents, but is costly | Rarely needed in lists |
Ids must also be unique within the list. Two siblings with equal keys cause a "Duplicate keys found" error in debug builds.
Keeping state for rows that scroll away
Because off-screen rows are disposed, state such as a text field's content or an expanded panel is lost when the row scrolls out and back. There are two reasonable fixes.
- Lift the state into the data. Store
selectedorexpandedin your model or state holder, and have the tile read it. This is the preferred fix. It survives disposal, and the tile can become stateless. - Keep the row alive. Mix
AutomaticKeepAliveClientMixininto the tile'sState, returntruefromwantKeepAlive, and callsuper.build(context)at the start ofbuild. Use this only for a few rows, such as a video player. Kept-alive rows stay in memory and keep their build and layout work.
Gotchas
shrinkWrap: true. It forces the list to measure all children to compute its own height, so laziness is lost. It is acceptable for short lists, not for long ones.- A list inside a
Column. WithoutExpandedyou get an unbounded-height error, and the common "fix" ofshrinkWrapbrings back the cost above. Wrap the list inExpanded. - Nested scrollables. A
ListViewinside aSingleChildScrollViewis measured eagerly. Use aCustomScrollViewwith slivers such asSliverList.builderto combine a header and a long list lazily. - Heavy work in
itemBuilder. The callback runs often while scrolling. Sorting, filtering, formatting, or parsing there repeats on every call. Do it once, outside the builder, and index into the result. - Rebuilding all rows from the parent. Lazy construction limits the number of rows, but a parent
setStatestill rebuilds every mounted row. If one row changes, push the changing state into that row (for example with aValueListenableBuilder) so the other rows stay untouched. constrows. Where a row needs no data, create it withconst. For data-driven rows you cannot useconst, but a tile that takes the sameproductinstance and compares equal in==is still cheap to rebuild.
Verify with measurements
Confirm the effect before and after. In a debug run, debugPrintRebuildDirtyWidgets = true lists the widgets rebuilt per frame, and you should see only the mounted rows. For frame times, use the DevTools Performance view on a profile-mode build, scroll quickly, and watch for jank frames. If frame cost does not move after a change, the list was not your bottleneck, and the change was not needed.
Exercise
A list of 500 tasks uses ListView.builder and no keys. Each tile is a StatefulWidget that keeps an "expanded" flag in its State. After the user sorts the list by due date, the wrong tasks appear expanded. Why does this happen, and what are two ways to fix it?
Show answer
Without keys, identity is positional. After the sort, the tile at each position keeps its old State, so the expanded flag stays at the position while the task data moves. Fix 1: give each tile key: ValueKey(task.id) and pass a findChildIndexCallback that maps the id to its new index, so the state follows the task. Fix 2: store the expanded flag in the task model or a state holder and make the tile read it, so no per-tile State is needed and the flag also survives scrolling out of the viewport.
Exercise
You see a screen with ListView(children: [for (final p in products) ProductTile(product: p)]) and 8,000 products, and scrolling stutters. What do you change first, and why would shrinkWrap: true on the replacement be a mistake?
Show answer
Switch to ListView.builder with itemCount: products.length and an itemBuilder that returns ProductTile(key: ValueKey(p.id), product: p), so only visible and nearby rows are built. If rows share a height, also set itemExtent. shrinkWrap: true makes the list measure every child to compute its own size, which brings back the cost of building and laying out all 8,000 rows.