Flutter ListView performance: pagination, images, caching
Keep long Flutter lists smooth: ListView.builder with itemExtent, Riverpod pagination without duplicate calls, LRU caches, cacheWidth images, DevTools checks.
On this page
A long Flutter list stays fast when it builds only what is on screen, knows its row height, loads pages on demand, decodes images at the size they are displayed and keeps memory bounded. In practice that means ListView.builder with itemExtent or prototypeItem, a paginated AsyncNotifier that never fires the same request twice, an LRU cache with a hard limit, cacheWidth on images, compression before upload and a debounced search. Each of those is a guess until DevTools confirms it on a real device.
Build only what is visible, and tell the list its row height
ListView(children: ...) builds every child up front. ListView.builder builds rows lazily as they approach the viewport, which is the minimum for any list that comes from an API.
Then give it the row size. With itemExtent, the viewport computes every position arithmetically instead of laying out children to find out where row 500 starts, so jumps, flings and the scrollbar stay cheap. If rows share a height you would rather not hard-code, prototypeItem measures one representative row instead. You can't pass both. If heights really vary, pass neither, because a wrong extent clips content. In a CustomScrollView the equivalents are SliverFixedExtentList and SliverPrototypeExtentList.
class ListingsList extends ConsumerWidget {
const ListingsList({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final async = ref.watch(listingsProvider);
return async.when(
loading: () => const ListingsSkeleton(),
error: (e, _) => ErrorRetry(onRetry: () => ref.invalidate(listingsProvider)),
data: (state) => NotificationListener<ScrollNotification>(
onNotification: (n) {
if (n.metrics.extentAfter < 800) {
ref.read(listingsProvider.notifier).loadMore();
}
return false;
},
child: ListView.builder(
itemExtent: 112,
itemCount: state.items.length + (state.hasMore ? 1 : 0),
itemBuilder: (context, i) => i < state.items.length
? ListingTile(key: ValueKey(state.items[i].id), listing: state.items[i])
: const ListingTileSkeleton(),
),
),
);
}
}I request the next page from a scroll notification, not from itemBuilder. itemBuilder runs during layout, and Riverpod asserts if you modify a provider while the tree is building. The listener fires many times near the bottom of the list. That is fine as long as loadMore ignores the calls it can't honor.
Paginate in an AsyncNotifier that ignores duplicate calls
class ListingsState {
const ListingsState(this.items, this.nextCursor, {this.isLoadingMore = false});
final List<Listing> items;
final String? nextCursor;
final bool isLoadingMore;
bool get hasMore => nextCursor != null;
}
final listingsProvider =
AsyncNotifierProvider<ListingsNotifier, ListingsState>(ListingsNotifier.new);
class ListingsNotifier extends AsyncNotifier<ListingsState> {
@override
Future<ListingsState> build() async {
final page = await ref.watch(listingsRepositoryProvider).fetchPage(cursor: null);
return ListingsState(page.items, page.nextCursor);
}
Future<void> loadMore() async {
final current = state.value;
if (current == null || !current.hasMore || current.isLoadingMore) return;
final loading = ListingsState(current.items, current.nextCursor, isLoadingMore: true);
state = AsyncData(loading);
try {
final page = await ref
.read(listingsRepositoryProvider)
.fetchPage(cursor: current.nextCursor);
if (_isStale(loading)) return; // a refresh replaced the state meanwhile
state = AsyncData(ListingsState([...current.items, ...page.items], page.nextCursor));
} catch (_) {
if (!_isStale(loading)) state = AsyncData(current); // the next scroll retries
}
}
bool _isStale(ListingsState expected) =>
state.isLoading || !identical(state.value, expected);
}isLoadingMore is set synchronously, before the first await, so the next scroll notification returns immediately and only one request is in flight at a time. There are no timers and no flags in the widget.
It pages with a cursor rather than an offset. With ?offset=40, an item inserted on the server shifts every page and you get duplicates or gaps. An opaque cursor returned by the API stays stable. If the backend only offers offsets, de-duplicate by id when appending.
A refresh always wins. Pull-to-refresh is RefreshIndicator(onRefresh: () => ref.refresh(listingsProvider.future)), and if a page arrives after a refresh started, the identity check drops it instead of appending page 3 to a fresh page 1.
On failure the notifier restores the previous state, so the next scroll retries. If you want a visible "Retry" footer, add an error field to ListingsState instead of swallowing the error.
Every in-memory cache gets a maximum size
Lists invite caching: details of recently opened items, computed thumbnails, formatted results. A cache without a maximum size is a memory leak with good intentions. Dart's default Map is a LinkedHashMap that keeps insertion order, which is all an LRU needs:
class LruCache<K, V extends Object> {
LruCache({required this.maxEntries}) : assert(maxEntries > 0);
final int maxEntries;
final _entries = <K, V>{}; // LinkedHashMap: iteration follows insertion order
V? get(K key) {
final value = _entries.remove(key);
if (value != null) _entries[key] = value; // mark as most recently used
return value;
}
void put(K key, V value) {
_entries.remove(key);
_entries[key] = value;
while (_entries.length > maxEntries) {
_entries.remove(_entries.keys.first); // evict the least recently used
}
}
void clear() => _entries.clear();
}A count limit is fine when entries are roughly the same size. When they are not, track an approximate byte size and evict on that. Flutter's own image cache works that way, with PaintingBinding.instance.imageCache.maximumSize (entries) and maximumSizeBytes.
This in-memory cache is a separate layer from HTTP caching. For responses I use a TTL with stale-while-revalidate behind a Dio interceptor, which is what I built smart_cache_plus for. Data the user must see fresh, such as availability, gets a short TTL or no cache at all.
Images: decode small, upload small
Decode at display size
A 4000 x 3000 photo decodes to 4000 x 3000 x 4 bytes, about 48 MB of RGBA, even when it is shown as a 96-pixel thumbnail. Put twenty of those in a list and the image cache evicts constantly, or the OS kills the app.
Image.network, Image.file and Image.asset accept cacheWidth and cacheHeight, which tell the engine to decode at that size. I compute it from the layout size and the pixel ratio: cacheWidth: (96 * MediaQuery.devicePixelRatioOf(context)).round(). Setting only one dimension keeps the aspect ratio. Any other ImageProvider can be wrapped in ResizeImage(provider, width: ...), and cached_network_image exposes the same idea as memCacheWidth.
To find offenders, set debugInvertOversizedImages = true in a debug build. Images decoded much larger than their display size then render inverted and flipped. The Flutter Inspector in DevTools has a toggle for the same overlay.
There is a cost. A thumbnail decoded at 288 pixels is useless in a zoomable gallery, so the detail screen asks for its own, larger decode. Two sizes of the same URL are two cache entries, and that is intended.
Compress before upload
Forms with photos, like listing creation in a real-estate app, should never upload raw camera files. I resize so the longest side fits what the server needs, re-encode as JPEG, and upload one file at a time instead of holding every original in memory.
There are two ways to do it. flutter_image_compress uses the platform codecs, so it is fast and handles formats like the HEIC files iPhones produce. The pure Dart image package works everywhere and is easy to test, but decoding is CPU-heavy, it can't read HEIC, and it has to run off the UI isolate:
import 'dart:isolate';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:image/image.dart' as img;
Future<Uint8List> compressForUpload(Uint8List bytes, {int maxSide = 1920}) {
return Isolate.run(() {
final decoded = img.decodeImage(bytes);
if (decoded == null) throw const FormatException('Unsupported image format');
var image = img.bakeOrientation(decoded); // apply EXIF rotation first
if (math.max(image.width, image.height) > maxSide) {
image = image.width >= image.height
? img.copyResize(image, width: maxSide)
: img.copyResize(image, height: maxSide);
}
return img.encodeJpg(image, quality: 80);
});
}It is a top-level function on purpose, so the closure captures only bytes and maxSide. Inside a class method, the closure can capture this and everything it references. At best that copies more than needed. At worst it reaches an object that can't cross isolates, like a socket or a ReceivePort, and throws.
bakeOrientation rotates the pixels according to the EXIF orientation tag, so portrait photos stay upright even when a server strips the metadata. On the web, Isolate.run is unavailable; compute from foundation works there but runs on the main thread.
Debounce the search and cancel the stale request
Typing "villa" should not fire five requests. A debouncer that cancels its pending timer on every keystroke keeps only the last one:
class Debouncer {
Debouncer(this.delay);
final Duration delay;
Timer? _timer;
void run(void Function() action) {
_timer?.cancel(); // only the last call within [delay] survives
_timer = Timer(delay, action);
}
void dispose() => _timer?.cancel();
}
final searchQueryProvider = NotifierProvider<SearchQuery, String>(SearchQuery.new);
class SearchQuery extends Notifier<String> {
@override
String build() => '';
void set(String value) => state = value.trim();
}
final searchResultsProvider = FutureProvider.autoDispose<List<Listing>>((ref) async {
final query = ref.watch(searchQueryProvider);
if (query.length < 2) return const [];
final cancelToken = CancelToken(); // Dio
ref.onDispose(cancelToken.cancel); // a newer query cancels this request
return ref.watch(listingsRepositoryProvider).search(query, cancelToken: cancelToken);
});The TextField calls _debouncer.run(() => ref.read(searchQueryProvider.notifier).set(text)), and the widget's dispose calls _debouncer.dispose(). Riverpod takes care of out-of-order responses: when the query changes, the provider rebuilds, the previous request is cancelled and its late result is ignored.
I don't debounce filters over a list that is already in memory. Filtering locally is instant, and the delay only feels like lag.
Boring build methods, and skeletons instead of spinners
Rows rebuild often, so I keep their build methods boring:
constconstructors wherever the inputs are compile-time constants. Flutter skips rebuilding a subtree when it receives the identical widget instance.- A
NumberFormatorDateFormatcreated per row, per frame, adds up. I create it once, in astatic finalor a provider. - Sorting, grouping and filtering happen in the notifier, once per change, not in
build. - Narrow watches.
ref.watch(listingsProvider.select((s) => s.value?.items.length))rebuilds a header only when the count changes.
While loading, I show skeleton rows with the same height as the real ones, for the first page and for the "loading more" footer. The layout doesn't jump when data arrives, and the screen reads as progress rather than a blocked page. Every shimmer runs off one shared animation, not one controller per row. When data comes from a local database and is almost always there before the first frame, I skip the skeleton, since it would only flash.
Measure in profile mode, on a real device
Everything above is a hypothesis until it is measured on a real device in profile mode (flutter run --profile). Debug builds use a JIT and extra checks, so their timings mean little.
The frame chart in the Performance view shows each frame's UI and raster time and highlights frames over budget. A slow UI thread points to build and layout work. A slow raster thread points to images, clips, shadows or saveLayer.
For rebuilds, I turn on widget build tracking (the Rebuild Stats tab in the Performance view, or the Flutter Performance panel in the IDE) and scroll. A header that rebuilds on every scroll tick is where select or const pays off.
For memory, I scroll to the end and back a few times with the Memory view open. Memory should plateau. If it keeps climbing, look for an unbounded cache or oversized images.
In production I add Firebase Performance custom traces around page loads, so the numbers come from users' devices and not only from mine.