What is the Image Widget?
The Image widget in Flutter displays images from various sources: network URLs, local assets, device file system, or memory. It's a versatile widget that supports many display options, including fit, alignment, repeat, and error handling. Images are loaded asynchronously, and Flutter provides built‑in caching for network images.
Image Constructors
Flutter provides several named constructors to load images from different sources:
Image.network: Loads an image from a URL.
Image.asset: Loads an image from the app's asset bundle.
Image.file: Loads an image from a file on the device.
Image.memory: Loads an image from aUint8List(byte array).
Image: Takes anImageProviderfor more advanced use.
Image from Network
Network images are cached automatically by Flutter's image cache (up to a limit). You can also control caching with cacheWidth and cacheHeight to downscale the image before decoding.
Image from Assets
First, declare the asset in pubspec.yaml. Then reference it with Image.asset. Flutter automatically selects the correct resolution variant based on the device pixel ratio if you organise images with 2.0x, 3.0x folders.
Image from File
For images from the device file system (e.g., a photo picked by the user), use Image.file. You'll need a File object from dart:io.
Controlling Image Fit
The fit property determines how the image is inscribed into the available space. Common values:
BoxFit.cover: Scales the image to fill the entire box, cropping if necessary.
BoxFit.contain: Scales the image to fit within the box while preserving aspect ratio (may leave empty space).
BoxFit.fill: Stretches the image to fill the box, possibly distorting it.
BoxFit.fitWidth: Scales to match the box's width, cropping height if needed.
BoxFit.fitHeight: Scales to match the box's height, cropping width if needed.
Alignment
When the image is larger than the available space, alignment controls how it is positioned within the box. For example, Alignment.topLeft anchors the image to the top left.
Error Handling
You can handle loading errors with the errorBuilder and frameBuilder. errorBuilder is called when the image fails to load; frameBuilder can show a placeholder while loading.
Caching and Performance
Flutter's Image.network uses a memory cache. To have more control over caching (e.g., disk cache), use the cached_network_image package. For large images, set cacheWidth and cacheHeight to avoid decoding the full image.
Key Takeaways
- Use
Image.networkfor remote images,Image.assetfor bundled assets,Image.filefor local files.
- Use
- Control image scaling with
fitand positioning withalignment.
- Control image scaling with
- Provide
errorBuilderandframeBuilderfor a better user experience.
- Provide
- Optimise memory usage with
cacheWidthandcacheHeight.
- Optimise memory usage with
- For advanced caching, consider
cached_network_image.
- For advanced caching, consider