Sub topic 15
Keeping long lists fast
This chapter assumes you can build a ListView.builder, you know the difference between a StatelessWidget and a StatefulWidget, and you have run an app in profile mode at least once. It covers why lazy lists are cheap, what still makes them slow, and how to measure the difference.
How lazy building keeps lists cheap
A ListView.builder does not create one widget per item. The viewport asks the list to build only the indexes that are visible, plus a small buffer past each edge. As you scroll, items that leave the buffer are disposed, and new indexes are built.
For a list of 100,000 rows with about 12 on screen, Flutter builds and lays out roughly 15 to 20 rows. The cost of a frame depends on the number of visible rows, not on itemCount.
Three consequences follow from this model:
itemBuilderruns many times, often once per row as it scrolls into view, so it must be cheap.- Row widgets do not live long. Any state held in a row's
Stateis lost when the row is disposed, unless you keep it elsewhere. - Anything that forces Flutter to measure or build every row defeats the whole mechanism.
Mistakes that remove the laziness
Building the children up front
The default ListView constructor takes a finished list of widgets. Passing List.generate(10000, ...) creates all 10,000 widgets before the first frame.
import 'package:flutter/material.dart';
class EagerList extends StatelessWidget {
const EagerList({super.key});
@override
Widget build(BuildContext context) {
// Creates 10,000 ListTile widgets immediately, even though
// only a dozen are visible.
return ListView(
children: List.generate(
10000,
(i) => ListTile(title: Text('Row $i')),
),
);
}
}Replace it with ListView.builder and an itemCount. Use the default constructor only for short lists whose length is known up front.
Using shrinkWrap on a long list
shrinkWrap: true makes the list size itself to its content. To do that, it must measure every child, so it builds all of them. A long list with shrinkWrap behaves like the eager example above, and the work repeats whenever the list changes.
The same applies to a ListView inside a SingleChildScrollView, or a Column of thousands of children. If the error that sent you to shrinkWrap was an unbounded height, fix the constraints with Expanded, or use a CustomScrollView with slivers.
Doing heavy work in itemBuilder
Because itemBuilder runs during scrolling, any work in it competes with the 16 ms frame budget (at 60 Hz). Common culprits are:
- Parsing dates or JSON for each row.
- Sorting or filtering the data set inside
build. - Creating a new
ScrollController,FutureorTextEditingControllerfor each build.
Prepare the data before the list is built. Convert raw records into display-ready objects when the data arrives, and keep that list in state. In itemBuilder, only read from it.
Tell the list how big the rows are
When all rows have the same height, itemExtent lets the list skip measuring each child. It computes the scroll extent and the position of each index with arithmetic. Jumping to a far-away position also becomes cheap.
import 'package:flutter/material.dart';
class Item {
const Item(this.id, this.title);
final int id;
final String title;
}
class FastList extends StatelessWidget {
const FastList({super.key, required this.items});
final List<Item> items;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemExtent: 56,
itemBuilder: (context, index) {
final item = items[index];
return ListTile(
key: ValueKey(item.id),
title: Text(item.title),
);
},
);
}
}If the row height is the same but you do not want to hard-code it, prototypeItem takes a sample widget and uses its extent for every row. You cannot set both itemExtent and prototypeItem. Neither suits rows whose heights differ, such as chat bubbles. For those, leave both unset and accept the measuring cost for the visible rows.
The key in the example is also worth having. When items are inserted or removed, stable keys let Flutter match existing elements to the right data instead of rebuilding them. For large lists that reorder often, findChildIndexCallback lets you map a key back to its new index. Look it up in a precomputed Map, because a linear search per call can cost more than it saves.
Keep each row cheap
A row costs build, layout and paint. These habits reduce all three:
- Mark widgets
constwhere possible. Aconst Icon(Icons.mail)is created once and shared. - Move large row layouts into their own
StatelessWidgetclass instead of a helper method. Flutter can then skip rebuilding a row whose inputs did not change. - Avoid
Opacity,ClipRRectwithsaveLayerand large shadows in every row. They are expensive to paint. Prefer a color with alpha, orCardwith a small elevation. - Do not call
setStateon a parent that owns the whole list for a change that affects one row. Give the row its own small state, or use aValueListenableBuilderaround the part that changes.
Images are the usual bottleneck
A 4000-pixel photo shown in an 80-pixel thumbnail is decoded at full size unless you say otherwise. Decoded images are held in memory, so a feed of such photos uses a lot of RAM and scrolls badly. Pass cacheWidth (or cacheHeight) to decode at a smaller size. These values are in physical pixels, so multiply by the device pixel ratio.
import 'package:flutter/material.dart';
class Thumbnail extends StatelessWidget {
const Thumbnail({super.key, required this.url});
final String url;
@override
Widget build(BuildContext context) {
final ratio = MediaQuery.devicePixelRatioOf(context);
return Image.network(
url,
width: 80,
height: 80,
fit: BoxFit.cover,
cacheWidth: (80 * ratio).round(),
);
}
}Buffer size, repaint boundaries and keep-alive
Three parameters tune how much work happens ahead of time or is retained.
| Setting | Default | Effect | When to change it |
|---|---|---|---|
| `cacheExtent` | 250 logical pixels on each side | Distance past the viewport edge where items are already built | Raise it a little if fast flings show blank rows. Lower it if rows are expensive and memory is tight. |
| `addRepaintBoundaries` | `true` | Wraps each row in a `RepaintBoundary` so one row repainting does not repaint its neighbors | Set to `false` only when rows are trivial and you have measured a gain. |
| `addAutomaticKeepAlives` | `true` | Lets a row ask to survive when scrolled off screen, for example a row with a playing video | Set to `false` if no row needs it, to avoid retaining rows. |
A large cacheExtent is not free. Raising it to several screens builds many more rows per scroll, which moves cost from "late rows" to "slower frames".
If a row must keep its state off screen, mix AutomaticKeepAliveClientMixin into its State and return true from wantKeepAlive. Use it sparingly. Every kept row stays in memory. For most cases, store the state (a selected flag or a text value) in the data model instead.
Measure before tuning
Debug mode is much slower than release, so frame times from a debug run say little. Use profile mode on a real device:
- Run
flutter run --profileon a physical device. - Open DevTools and select the Performance view.
- Scroll the list quickly and look for frames over the budget. The UI thread shows build and layout time. The raster thread shows paint and image cost.
- If the UI thread is slow, look at
itemBuilderand layout. If the raster thread is slow, look at images, clips, opacity and shadows.
Change one thing at a time and compare. A fix that does not move the numbers is not worth keeping.
Exercise
A screen shows a feed of 5,000 rows in a Column, and the first frame takes over a second. A teammate "fixed" an earlier overflow error by wrapping a ListView.builder in a SingleChildScrollView and setting shrinkWrap: true. Why is it still slow, and what two changes fix it? Add one more change that helps if every row is the same height.
Show answer
shrinkWrap: true forces the list to measure all 5,000 children, so none of them are built lazily, and the SingleChildScrollView gives the list unbounded height for the same reason. Remove both. Put the ListView.builder inside Expanded in the Column, or into a CustomScrollView with slivers, so it receives a bounded height from its parent. For same-height rows, set itemExtent (or prototypeItem) so the list can skip measuring each child.
Exercise
Each row of a photo list shows a 4000x3000 network image in an 80x80 box. Scrolling stutters and memory climbs. Which parameter on Image.network helps, what unit does it use, and how do you compute its value?
Show answer
Use cacheWidth (or cacheHeight). It is in physical pixels, so compute it as 80 multiplied by the device pixel ratio, for example (80 * MediaQuery.devicePixelRatioOf(context)).round(). The image is then decoded at thumbnail size instead of full size.