Sub topic 8
Displaying images with the Image widget
This chapter introduces the Image widget: what it is, how it turns a source into pixels, and the properties and mistakes you will meet first. It assumes you can write a StatelessWidget, know that pubspec.yaml configures a project, and can run a Flutter app on an emulator, device, or the web. Later chapters cover each image source, BoxFit, loading states, and caching in detail. Here you build the working model they rely on.
What the Image widget does
Image is a widget that paints a bitmap, such as a PNG, JPEG, GIF, WebP, or BMP file. It does not know where the bytes come from. That job belongs to an ImageProvider, an object that describes an image source and knows how to fetch and decode it.
The pipeline has four steps:
- You give
ImageanImageProvider, directly or through a named constructor. - The widget asks the provider for an
ImageStream. The stream may emit one frame (a PNG) or many (an animated GIF). - The provider checks the global
ImageCache. On a miss, it loads and decodes the bytes. - The widget receives a decoded image and paints it through a lower-level widget,
RawImage.
This model explains behaviors that otherwise look odd. Loading is asynchronous, so an image can appear a frame or more after the widget first builds. Two Image widgets with the same provider share one decoded copy. A source that fails produces an error, not a blank space.
Constructors are shortcuts for providers
The named constructors each build a provider for you.
| Constructor | Provider it creates | Source |
|---|---|---|
| `Image.asset` | `AssetImage` | A file bundled with the app |
| `Image.network` | `NetworkImage` | A URL |
| `Image.file` | `FileImage` | A file on the device (not available on the web) |
| `Image.memory` | `MemoryImage` | A `Uint8List` of encoded bytes |
| `Image(image: ...)` | Any `ImageProvider` you pass | Anything |
These two widgets are equivalent:
const Image(image: AssetImage('assets/images/hero.png'))
Image.asset('assets/images/hero.png')Use the plain Image(image: ...) form when you need a provider that the named constructors do not wrap. Examples are a provider you wrote yourself or one from a package, such as a cached-network-image provider. A provider is also what you pass to precacheImage and to DecorationImage, so knowing it exists pays off beyond this widget.
A first runnable example
This complete app draws a tiny embedded PNG. Image.memory needs no asset registration and no network, so it runs anywhere. The source is a 1x1 pixel image, enlarged to 120x120 logical pixels so you can see how sizing works.
import 'dart:convert';
import 'package:flutter/material.dart';
const _pixelPng =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
void main() => runApp(const MaterialApp(home: ImageDemo()));
class ImageDemo extends StatelessWidget {
const ImageDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Image demo')),
body: Center(
child: Image.memory(
base64Decode(_pixelPng),
width: 120,
height: 120,
fit: BoxFit.fill,
filterQuality: FilterQuality.none,
semanticLabel: 'A single enlarged pixel',
),
),
);
}
}filterQuality: FilterQuality.none keeps the enlarged pixel sharp. The default is FilterQuality.low, which smooths scaled images. For photos, leave the default.
Size: the properties you set first
The properties you will use most are width, height, fit, and semanticLabel.
widthandheightare measured in logical pixels, not physical ones. A phone with a device pixel ratio of 3 draws a 100-wide image across 300 physical pixels.- If you set neither, the image asks for its intrinsic size, which is its pixel dimensions divided by its resolution scale. A 4000-pixel-wide photo can ask for a very wide box.
- If you set only one, the image keeps its aspect ratio and computes the other.
- If you set both, the box has that exact size. How the picture fills the box depends on
fit, covered in its own chapter.
The incoming constraints from the parent also apply. A parent can force a size that differs from the one you requested. For example, a SizedBox with tight constraints overrides width and height on its child.
Common errors and how to read them
The asset is not found
The exception reads Unable to load asset: "assets/images/hero.png". There are three usual causes. The path in code differs from the file on disk, which is case-sensitive on most platforms. The folder is not listed under flutter: assets: in pubspec.yaml. Or you added the entry but only hot reloaded. Asset changes need a full restart, and sometimes flutter clean followed by a rebuild.
flutter:
assets:
- assets/images/The trailing slash registers every file directly inside that folder. It does not include subfolders. List each subfolder on its own line.
The image overflows its parent
Inside a Row, an image with a large intrinsic width ignores the remaining space, and you get the yellow-and-black overflow stripes. Give the image a bounded size, or wrap it in Expanded or Flexible:
Row(
children: [
Expanded(
child: Image.asset('assets/images/hero.png', fit: BoxFit.cover),
),
const Icon(Icons.chevron_right),
],
)The image is blurry or pixelated
A source smaller than its box gets stretched. A source much larger than its box wastes memory, though it usually looks fine. Match source resolution to display size, taking the device pixel ratio into account. Resolution variants for assets are a separate topic.
Nothing shows and no error appears
Check for zero-sized constraints. An image inside an unconstrained parent that gives it zero height, or a Container with no size and no child content, can paint nothing. Open Flutter DevTools and use the widget inspector to read the actual size of the Image.
Errors and loading, briefly
The bare widget shows nothing while it loads, and it throws an error to the framework if loading fails. The loadingBuilder and errorBuilder parameters let you show a placeholder and a fallback, and a later chapter covers them. For now, remember that you can ask for the image's frames directly with frameBuilder, which is the hook for fade-in animations, and that gaplessPlayback: true keeps the old image on screen while a new provider loads. Without it, changing the provider makes the picture flicker.
Image is not free
Decoded images are the largest memory consumers in many apps. A 4000 x 3000 photo takes about 48 MB once decoded to RGBA, regardless of its size on disk or on screen. The ImageCache holds up to 1000 images and 100 MB by default, and it evicts the least recently used ones when it exceeds either limit. Chapter-level techniques such as cacheWidth and precacheImage exist to control this. At this stage, the working rule is to never load a source much larger than you display it.
Exercise
An Image.asset('assets/images/logo.png') works on your machine, but a teammate who pulled your branch sees "Unable to load asset". The file exists on their disk at the same path. Name two things to check, and say what Image.asset is equivalent to when written with the plain constructor.
Show answer
Check that assets/images/ (or the exact file) is listed under flutter: assets: in pubspec.yaml and committed, and that the teammate did a full restart or rebuild instead of a hot reload. Also check for a case mismatch in the file name, since asset lookup is case-sensitive. Image.asset('assets/images/logo.png') is equivalent to Image(image: AssetImage('assets/images/logo.png')).
Exercise
You place an Image.network with no width or height inside a Row, next to a Text. The row overflows when a large photo loads. Give two fixes.
Show answer
Wrap the image in Expanded or Flexible so the row's remaining width bounds it. Alternatively, give the image an explicit width (and optionally height) small enough to fit, or put it inside a SizedBox.