Sub topic 12
Handling loading and error states
Network images are slow and sometimes fail. This chapter shows how to give users feedback while an image loads, a fallback when it fails, and a smooth transition between the two. It assumes you can already create an Image.network widget, size it with width, height, and fit, and write a StatefulWidget.
The working model
An Image widget does not show pixels instantly. It asks an image provider for an image stream, and that stream moves through stages. The widget exposes three builder callbacks, one for each concern.
| Callback | Called when | Key arguments |
|---|---|---|
| `loadingBuilder` | Download progress changes, and once more when it ends | `child`, `ImageChunkEvent? loadingProgress` |
| `frameBuilder` | A decoded frame is ready, or before the first frame | `child`, `int? frame`, `bool wasSynchronouslyLoaded` |
| `errorBuilder` | The request or decoding throws | `Object error`, `StackTrace? stackTrace` |
loadingBuilder covers Downloading. frameBuilder covers Decoding and the arrival of the first frame. errorBuilder covers Failed.
loadingBuilder
The loadingBuilder runs on every progress update. Its contract is simple: when loadingProgress is null, loading is finished and you must return the child it gave you. Otherwise, return your placeholder.
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
final total = progress.expectedTotalBytes;
return Center(
child: CircularProgressIndicator(
value: total == null ? null : progress.cumulativeBytesLoaded / total,
),
);
},expectedTotalBytes is nullable because the server may not send a Content-Length header. Passing value: null gives an indeterminate spinner, which is the correct fallback. Dividing without the null check is a common crash.
Chunk events come from network downloads. Asset, file, and memory images have nothing to download, so a loadingBuilder there tells you very little.
frameBuilder for smooth reveals
When a download ends, the loadingBuilder receives null progress and the image still has to decode. During that gap the child can be blank. The frameBuilder receives frame == null until the first frame is ready, so you can fade the image in.
Check wasSynchronouslyLoaded first. It is true when the image came straight from the cache, and in that case animating would make a cached image flicker in for no reason. Return the child unchanged.
errorBuilder
The errorBuilder replaces the whole image when loading or decoding fails. Typical causes are:
- A 404 or 500 response.
- No connectivity.
- A server that returns an HTML page with status 200. This causes a decode error.
- A file format Flutter cannot decode.
- On Flutter web, a server that lacks CORS headers.
Because it replaces the image, keep the fallback the same size as the image. Otherwise the layout jumps when the failure arrives.
A reusable widget with retry
This widget combines all three callbacks and adds a retry button. Changing the Key on the Image makes Flutter build a fresh state, which starts a new request. Failed loads are not kept in the image cache, so the retry reaches the network again.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(
body: Center(
child: NetworkPhoto(url: 'https://example.com/photo.jpg'),
),
),
),
);
class NetworkPhoto extends StatefulWidget {
const NetworkPhoto({
super.key,
required this.url,
this.width = 200,
this.height = 120,
});
final String url;
final double width;
final double height;
@override
State<NetworkPhoto> createState() => _NetworkPhotoState();
}
class _NetworkPhotoState extends State<NetworkPhoto> {
int _attempt = 0;
@override
Widget build(BuildContext context) {
return SizedBox(
width: widget.width,
height: widget.height,
child: Image.network(
widget.url,
key: ValueKey(_attempt),
width: widget.width,
height: widget.height,
fit: BoxFit.cover,
semanticLabel: 'Photo',
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
if (wasSynchronouslyLoaded) return child;
return AnimatedOpacity(
opacity: frame == null ? 0 : 1,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
child: child,
);
},
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
final total = progress.expectedTotalBytes;
return Center(
child: CircularProgressIndicator(
value:
total == null ? null : progress.cumulativeBytesLoaded / total,
),
);
},
errorBuilder: (context, error, stackTrace) {
return ColoredBox(
color: Colors.black12,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.broken_image),
TextButton(
onPressed: () => setState(() => _attempt++),
child: const Text('Retry'),
),
],
),
),
);
},
),
);
}
}Flutter applies the callbacks in a fixed order. The frameBuilder runs first and produces a child. The loadingBuilder then wraps that result. If an error occurred, the errorBuilder output replaces everything. That is why returning child when progress == null keeps the fade-in working.
Errors in other sources
errorBuilder is available on Image.asset, Image.file, and Image.memory too. It matters most for Image.memory and Image.file, where the bytes may be corrupt or missing. A missing asset entry in pubspec.yaml also ends up in errorBuilder, so a broken-image fallback can hide a configuration mistake during development. Check the debug console while testing.
For images you preload with precacheImage, pass its onError argument. Otherwise a failed warm-up has no handler.
Common errors
- Returning the placeholder when
progress == null. The spinner then never goes away. - Dividing by
expectedTotalByteswithout a null check. This throws when the server omits the content length. - Calling
setStatewhile building. Do it only inside anonPressedor other event callback, as the retry button does. - Reusing the same key on retry. The existing state keeps its failed stream, so nothing reloads.
- A fallback of a different size. The surrounding layout shifts when the error appears.
- Using a
constconstructor with callbacks. Closures are not constants, soImage.network(...)with builders cannot beconst.
Exercise
A network image shows an endless spinner after it finishes downloading. Its loadingBuilder is (context, child, progress) => const CircularProgressIndicator(). What is wrong, and how do you fix it?
Show answer
The builder ignores progress, so it always returns the spinner and never returns the image. Check if (progress == null) return child; first, then return the spinner only while loading. For a determinate bar, use progress.cumulativeBytesLoaded / progress.expectedTotalBytes, and guard against expectedTotalBytes being null.
Exercise
Why does the retry button in NetworkPhoto change the Image's key instead of only calling setState?
Show answer
A plain setState rebuilds the Image with the same configuration. Flutter then reuses the existing element and its state, which still holds the failed image stream. A new ValueKey makes Flutter create fresh state, which resolves the image again and sends a new request.