Sub topic 13
Image caching and memory use
This chapter assumes you can build Flutter widgets, you know how Image.asset and Image.network work, and you have set up BoxFit and image sizes. Here you will learn how Flutter keeps decoded images in memory, why a large file can cost much more memory than you expect, and how to control that cost.
How an image becomes memory
A compressed file (PNG, JPEG, WebP) is small on disk. To draw it, Flutter must decode it into raw pixels. Each pixel takes 4 bytes (red, green, blue, alpha). The memory cost depends on the pixel dimensions, not the file size:
memory ≈ width × height × 4 bytesA 4000 × 3000 photo can be a 2 MB JPEG, but it decodes to about 48 MB (4000 × 3000 × 4). Show twenty of them in a list and memory grows quickly. This is a common cause of slow scrolling and out-of-memory crashes on low-end devices.
The image cache
Flutter keeps decoded images in a shared in-memory cache, PaintingBinding.instance.imageCache. When two Image widgets ask for the same image, the second one reuses the decoded result instead of decoding again.
The cache has two limits. When either is exceeded, the least recently used images are evicted.
| Property | Default | Meaning |
|---|---|---|
| `maximumSize` | 1000 | Maximum number of images |
| `maximumSizeBytes` | 100 MiB | Maximum total decoded bytes |
The cache is only in memory. It is emptied when the app process ends. For Image.network, Flutter does not store the downloaded file on disk, so every app launch downloads the image again. Packages such as cached_network_image add a disk cache.
import 'package:flutter/widgets.dart';
void configureImageCache() {
final cache = PaintingBinding.instance.imageCache;
cache.maximumSizeBytes = 50 * 1024 * 1024; // 50 MiB
cache.maximumSize = 200;
}Call this after WidgetsFlutterBinding.ensureInitialized() in main, before runApp.
Decode smaller with cacheWidth and cacheHeight
By default Flutter decodes an image at its full pixel size, even if you display it in a 100 × 100 box. cacheWidth and cacheHeight tell the decoder to produce a smaller image. If you set only one, the other is computed to keep the aspect ratio.
import 'package:flutter/material.dart';
class Thumbnail extends StatelessWidget {
const Thumbnail({super.key});
@override
Widget build(BuildContext context) {
final dpr = MediaQuery.devicePixelRatioOf(context);
const logicalSize = 100.0;
return Image.asset(
'assets/images/hero.png',
width: logicalSize,
height: logicalSize,
fit: BoxFit.cover,
cacheWidth: (logicalSize * dpr).round(),
);
}
}The values are in physical pixels, so multiply the logical size by the device pixel ratio. On a screen with a ratio of 3, a 100-point box needs 300 pixels to look sharp. Setting cacheWidth: 100 there would make the image blurry.
The cache key includes the decode size. The same file shown with two different cacheWidth values is stored as two separate entries.
Gotchas
- Decoding at a small size is permanent for that widget. If the user can zoom in, a small
cacheWidthgives a blurry result. - Do not set both
cacheWidthandcacheHeightunless you want to force that exact size. Setting both can distort the aspect ratio. Set one. cacheWidthreduces memory, but it does not reduce the download size of a network image. The full file is still fetched.
Warm the cache with precacheImage
The first time an image is shown, there is a delay while it loads and decodes. The image may pop in. precacheImage loads and decodes an image ahead of time and places it in the cache, so it shows instantly later.
It needs a BuildContext and an ImageProvider. Use didChangeDependencies rather than initState, because precacheImage reads inherited data from the context.
import 'package:flutter/material.dart';
class SplashThenHome extends StatefulWidget {
const SplashThenHome({super.key});
@override
State<SplashThenHome> createState() => _SplashThenHomeState();
}
class _SplashThenHomeState extends State<SplashThenHome> {
static const _hero = AssetImage('assets/images/hero.png');
bool _precached = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_precached) {
_precached = true;
precacheImage(_hero, context);
}
}
@override
Widget build(BuildContext context) {
return const Image(image: _hero, width: 300, height: 180);
}
}The _precached flag stops the call from repeating each time dependencies change. The widget that later displays the image must use an equal provider (same asset name and same decode size) or it will not hit the cached entry.
If you display the image with cacheWidth, precache the same size. Wrap the provider with ResizeImage:
precacheImage(
ResizeImage(const AssetImage('assets/images/hero.png'), width: 600),
context,
);precacheImage returns a Future. If loading fails, the future completes with an error unless you pass an onError callback.
Clearing and evicting
You can remove images from the cache by hand, for example after a user signs out or when you receive a memory warning.
final cache = PaintingBinding.instance.imageCache;
// Remove everything that has finished loading.
cache.clear();
// Remove one image by its provider key.
await const AssetImage('assets/images/hero.png').evict();
// Inspect the cache.
debugPrint('${cache.currentSize} images, '
'${cache.currentSizeBytes} bytes');ImageProvider.evict() returns a Future<bool> that is true if the image was in the cache. Flutter already clears the cache on low-memory notifications from the platform, so manual clearing is rarely needed.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Memory spikes when scrolling a photo list | Full-resolution decode of every image | Set `cacheWidth` per thumbnail |
| Images reload when you scroll back | Cache limits are too low, or the widget is rebuilt with a different provider | Raise `maximumSizeBytes`, or keep provider values stable |
| Image is blurry on a high-density screen | `cacheWidth` set in logical pixels | Multiply by `devicePixelRatio` |
| `precacheImage` has no visible effect | Different provider or decode size than the displayed image | Use an identical provider, or `ResizeImage` with the same width |
| Network images download on every launch | Flutter has no disk cache | Use a disk-caching package |
Decision criteria
- Show a small image in a large list: use
cacheWidth. - An image must appear instantly on a later screen: use
precacheImagewith the same provider. - Full-screen zoomable photos: keep full resolution and accept the memory cost, but show one or two at a time.
- Images needed across app launches: add a disk cache package, because the built-in cache is memory only.
- Tuning cache limits: measure first with
currentSizeBytesor the DevTools memory view, then changemaximumSizeBytes.
Exercise
A 3000 × 2000 pixel photo is shown in a 120 × 80 logical-pixel box on a device with a pixel ratio of 3. About how much memory does the default decode use, and what cacheWidth should you set to keep the image sharp while saving memory?
Show answer
The default decode uses about 3000 × 2000 × 4 = 24,000,000 bytes (about 24 MB). The box needs 120 × 3 = 360 physical pixels of width, so set cacheWidth: 360. The decoded image is then 360 × 240 × 4 = 345,600 bytes, about 0.35 MB.
Exercise
You call precacheImage(const AssetImage('assets/images/hero.png'), context) but the screen later shows the image with Image.asset('assets/images/hero.png', cacheWidth: 600) and still flickers on first display. Why, and how do you fix it?
Show answer
The displayed image is decoded at width 600, so its cache key differs from the full-size entry you precached. Precache with ResizeImage(const AssetImage('assets/images/hero.png'), width: 600) so both use the same key.