Sub topic 9
Loading images from assets, network, files, and memory
Flutter's Image widget can draw pixels from four places: files bundled with the app, a URL, a file on the device, and bytes already in memory. This chapter covers the constructor for each source and the setup each one needs. It also covers the platform errors that appear when that setup is missing.
It assumes you can write a StatelessWidget and read pubspec.yaml. It also assumes you have a Flutter project that runs on an emulator, a device, or the web.
One widget, four constructors
Each constructor of Image builds an ImageProvider. The provider describes where the bytes come from and how to decode them. The widget handles layout, painting, and the image cache.
| Constructor | Provider | Source | Web support |
|---|---|---|---|
| `Image.asset` | `AssetImage` | Files bundled in the app | Yes |
| `Image.network` | `NetworkImage` | HTTP or HTTPS URL | Yes, subject to CORS |
| `Image.file` | `FileImage` | A `File` on the device | No |
| `Image.memory` | `MemoryImage` | A `Uint8List` of encoded bytes | Yes |
Use the provider classes directly when an API wants a provider instead of a widget. Examples are DecorationImage, CircleAvatar.backgroundImage, and precacheImage. You can also wrap a provider in the widget with Image(image: provider).
Assets
An asset image needs two things. The file must exist in your project, and pubspec.yaml must list it. The assets entry from the spine's example registers a whole folder:
flutter:
uses-material-design: true
assets:
- assets/images/A trailing slash includes the files directly inside that folder but not its subfolders. List each subfolder on its own line. After you change pubspec.yaml, stop the app and run it again. Hot reload does not pick up new assets.
Image.asset(
'assets/images/hero.png',
width: 300,
height: 180,
fit: BoxFit.cover,
semanticLabel: 'Mountain landscape at sunrise',
)The path is the key in the asset bundle. It must match the pubspec.yaml path exactly, including the assets/ prefix and the letter case. A wrong path throws an exception that reads "Unable to load asset". Android and web treat filenames as case-sensitive, so a mismatch that works on a Mac can fail elsewhere.
Assets that ship inside a package need the package argument:
Image.asset(
'assets/images/logo.png',
package: 'my_design_kit',
)Flutter also supports resolution variants such as 2.0x/hero.png. The next chapter covers them.
Network images
Image.network takes a URL and downloads, decodes, and caches the image. Nothing extra is needed in Dart:
Image.network(
'https://example.com/photo.jpg',
width: 200,
height: 120,
fit: BoxFit.cover,
)The headers parameter sends extra request headers, such as an authorization token for a private image. The widget shows nothing until the image arrives, so you should also handle loading and failure states. The chapter on loading and error states covers loadingBuilder and errorBuilder.
Network images most often fail because of platform configuration:
- Android release builds. The debug and profile manifests include the
INTERNETpermission, but the main manifest does not. Add<uses-permission android:name="android.permission.INTERNET"/>toandroid/app/src/main/AndroidManifest.xml. Without it, images load in debug and fail in release. - iOS and Android cleartext. Plain
http://URLs are blocked by default (App Transport Security on iOS, cleartext rules on Android). Preferhttps://. - macOS. Enable the
com.apple.security.network.cliententitlement in both entitlement files. - Web. The browser enforces CORS. If the image server does not send suitable
Access-Control-Allow-Originheaders, the request can fail even though the same URL opens in a browser tab.
Files on the device
Image.file takes a dart:io File. It is common for photos from a camera or picker, and for files in a directory from path_provider:
import 'dart:io';
import 'package:flutter/material.dart';
class LocalPhoto extends StatelessWidget {
const LocalPhoto({super.key, required this.path});
final String path;
@override
Widget build(BuildContext context) {
return Image.file(
File(path),
width: 200,
height: 200,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) =>
const Icon(Icons.broken_image),
);
}
}On the web there is no file system, so Image.file throws an unsupported-operation error. If your app also targets the web, check kIsWeb from package:flutter/foundation.dart. Use Image.memory or Image.network on that branch.
A mobile OS can also restrict access to a path. The file must be inside your app's sandbox, or you must have permission to read it. FileImage caches by path and modification time, so overwriting a file at the same path usually refreshes it. You can also call FileImage(file).evict() to force a reload.
Bytes in memory
Image.memory takes a Uint8List of encoded image data, meaning PNG, JPEG, GIF, or WebP bytes. It does not take raw pixel values. Typical sources are a database blob, a base64 string from an API, or XFile.readAsBytes() from an image picker. The last one also works on the web.
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
// A 1x1 PNG, base64-encoded.
const _pixelBase64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
class MemoryPicture extends StatelessWidget {
const MemoryPicture({super.key});
@override
Widget build(BuildContext context) {
final Uint8List bytes = base64Decode(_pixelBase64);
return Image.memory(
bytes,
width: 100,
height: 100,
fit: BoxFit.fill,
gaplessPlayback: true,
);
}
}The gaplessPlayback: true option keeps the old image on screen while a new provider loads. Without it, the widget goes blank for a frame when the bytes change. It suits previews that update often.
Note that build decodes the base64 string every time it runs. For a large string, decode once and store the Uint8List in state. MemoryImage compares bytes by identity, and a fresh list every build forces a fresh decode.
Choosing a source
- Fixed art that ships with the app, such as logos and illustrations, belongs in assets.
- Content that changes without an app release, such as avatars and product photos, should come from the network.
- Images the user creates or picks go through files on mobile and desktop, or bytes on the web.
- Bytes from an API, a database, or generated data go through memory.
For network images that must survive restarts or work offline, the built-in cache lives only in memory for the current session. Packages such as cached_network_image add a disk cache.
Exercise
Your app shows a user's profile photo with Image.network. It works in debug mode on an Android phone but shows nothing in a release build. What is the most likely cause, and where do you fix it?
Show answer
The main AndroidManifest.xml lacks the INTERNET permission. Debug and profile builds get it from their own manifests, but release builds use only the main one. Add <uses-permission android:name="android.permission.INTERNET"/> to android/app/src/main/AndroidManifest.xml.
Exercise
A picker returns an XFile, and your app runs on both Android and the web. Which Image constructor works on both, and how do you get its input?
Show answer
Use Image.memory with the result of await xfile.readAsBytes(), which is a Uint8List. Image.file would fail on the web because the browser has no file system.