Working with Images
1. Using Image Widget
| Property | Values | Description |
|---|---|---|
| image | ImageProvider |
Image to display (required) |
| fit | BoxFit |
How to inscribe the image into the layout frame |
| alignment | Alignment |
Where to align the image within its container |
| repeat | ImageRepeat |
How to repeat the image if it's smaller than its container |
| centerSlice | Rect |
Region of the image to slice and repeat |
Example: Basic Image Display
import 'package:flutter/material.dart';
class MyImageWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Image Example")),
body: Center(
child: Image.asset("assets/images/flutter_logo.png"),
),
);
}
}
Image.network(). For local assets, use Image.asset().
2. Declaring Assets in pubspec.yaml
Images and other assets must be declared in the pubspec.yaml file to be included in the app build.
| Property | Values | Description |
|---|---|---|
| flutter.assets | assets/images/ |
Directory path to asset files. Supports wildcards like assets/images/**/*.png. |
| flutter.assets | assets/icons/icon.png |
Specific asset path. Must be relative to pubspec.yaml. |
Example: Declaring image assets
flutter:
assets:
- assets/images/logo.png
- assets/images/background.jpg
- assets/icons/
pubspec.yaml file and must be indented properly under flutter.assets.
3. Using AssetImage and NetworkImage Providers
| Property | Description | Usage |
|---|---|---|
| AssetImage | Loads images from the app's asset bundle. | Image.asset('assets/images/logo.png') |
| NetworkImage | Loads images from a URL over the network. | Image.network('https://example.com/image.png') |
Example: AssetImage Usage
import 'package:flutter/material.dart';
class ImageExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Asset Image")),
body: Center(
child: Image.asset(
'assets/images/flutter_logo.png',
width: 200,
height: 200,
),
),
);
}
}
Example: NetworkImage Usage
import 'package:flutter/material.dart';
class NetworkImageExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Network Image")),
body: Center(
child: Image.network(
'https://flutter.dev/assets/images/flutter-logo.png',
width: 200,
height: 200,
),
),
);
}
}
pubspec.yaml file under the assets section.
Image.network with a placeholder or error widget.
Key Differences
- AssetImage: Faster, cached locally; ideal for app assets.
- NetworkImage: Slower, requires internet; ideal for external images.
4. Setting Image Fit
| Property | Values | Description |
|---|---|---|
| fit | BoxFit.contain, BoxFit.cover, BoxFit.fill, BoxFit.fitHeight, BoxFit.fitWidth, BoxFit.none |
Determines how the image should be inscribed into the box. |
BoxFit.fill stretches the image to fill the available space, potentially distorting the aspect ratio.BoxFit.none displays the image at its original size, centered within the available space.5. Using width and height Properties
| Property | Values | Description |
|---|---|---|
| width | double |
Sets the width of the image widget. If not specified, the image will use its intrinsic width. |
| height | double |
Sets the height of the image widget. If not specified, the image will use its intrinsic height. |
Example: Setting width and height
Image.asset(
'assets/images/example.png',
width: 200.0,
height: 150.0,
)
6. Using Color and ColorBlendMode
| Property | Values | Description |
|---|---|---|
| color | Color(0xFF0000FF) |
Applies a color filter to the image |
| colorBlendMode | BlendMode.modulate |
Determines how the color is blended with the image |
Example: Applying Color and Blend Mode
Image.asset(
'assets/images/example.png',
color: Colors.blue,
colorBlendMode: BlendMode.modulate,
)
colorBlendMode affects how the color filter interacts with the original image colors.Common Blend Modes
BlendMode.modulate: Multiplies the color with the imageBlendMode.multiply: Darkens the image by multiplying colorsBlendMode.screen: Lightens the image by screening colors
7. Implementing Image Caching
Example: Using CachedNetworkImage
<CachedNetworkImage
imageUrl: "https://example.com/image.jpg",
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
/>
| Property | Description | Default |
|---|---|---|
| imageUrl | URL of the image to load | Required |
| placeholder | Widget to show while image is loading | null |
| errorWidget | Widget to show if image fails to load | null |
CachedNetworkImage automatically handles caching and uses memory and disk caches for performance.
8. Using CachedNetworkImage Package
The CachedNetworkImage package is a popular Flutter plugin that efficiently loads and caches images from the network. It provides a simple API to display images from URLs while automatically handling caching, loading indicators, and error states.
| Property | Description | Default Value |
|---|---|---|
| imageUrl | URL of the image to be loaded. | Required |
| placeholder | Widget to display while the image is loading. | None |
| errorWidget | Widget to display if the image fails to load. | None |
| cacheManager | Custom cache manager instance to use for caching. | Default cache manager |
Example: Basic usage of CachedNetworkImage
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
class ImageExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Cached Image Example")),
body: Center(
child: CachedNetworkImage(
imageUrl: "https://example.com/image.jpg",
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
);
}
}
cached_network_image dependency to your pubspec.yaml file.
Key Features
- Caching of images to reduce network usage.
- Support for loading and error placeholders.
- Automatic image resizing based on the widget size.
9. Using FadeInImage Widget
The FadeInImage widget in Flutter is used to display an image with a fade-in effect when the image is loaded. It's particularly useful for improving user experience by providing visual feedback while images are loading.
| Property | Description | Values |
|---|---|---|
| image | The image to display. This is typically a NetworkImage or AssetImage. |
ImageProvider |
| placeholder | The image to show while the main image is loading. | ImageProvider |
| fit | How to inscribe the image into the space allocated during layout. | BoxFit values (e.g., BoxFit.cover, BoxFit.contain) |
| fadeOutDuration | Duration of the fade-out animation before the image appears. | Duration |
| fadeInDuration | Duration of the fade-in animation when the image loads. | Duration |
Example: Basic usage of FadeInImage
import 'package:flutter/material.dart';
class MyImageWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FadeInImage(
placeholder: AssetImage("assets/placeholder.png"),
image: NetworkImage("https://example.com/image.jpg"),
fit: BoxFit.cover,
fadeInDuration: Duration(milliseconds: 500),
fadeOutDuration: Duration(milliseconds: 200),
);
}
}
placeholder image should ideally be a small, low-resolution version of the target image or a generic loading indicator to provide visual feedback during load.
10. Handling Image Errors
| Error Type | Description | Solution |
|---|---|---|
| Image not found | Image resource path is incorrect or file does not exist. | Verify the image path and ensure the file is included in the assets. |
| Invalid image format | Image file is corrupted or in an unsupported format. | Convert to a supported format like PNG or JPEG. |
| Network error (for web images) | Image fails to load due to network issues or URL errors. | Implement retry logic or fallback image using Image.network with errorBuilder. |
Example: Using errorBuilder for Network Images
Image.network(
'https://example.com/image.jpg',
errorBuilder: (context, error, stackTrace) {
return Text('Failed to load image');
},
)
errorBuilder is only available for Image.network and Image.asset. For custom image providers, implement error handling in the provider itself.
11. Using Image.frameBuilder for Loading States
The frameBuilder parameter in the Image widget allows you to customize how images are displayed during loading, providing a better user experience by showing placeholders or progress indicators.
| Property | Description | Usage |
|---|---|---|
| frameBuilder | Callback function to build the image widget with loading states. | frameBuilder: (BuildContext context, Widget child, int? frame, bool? isLoaded) |
Example: Using frameBuilder to show a loading indicator
Image.asset(
'assets/images/example.png',
frameBuilder: (BuildContext context, Widget child, int? frame, bool? isLoaded) {
if (isLoaded != null && !isLoaded) {
return const CircularProgressIndicator();
}
return child;
},
)
frameBuilder is particularly useful for images loaded from the network or assets that may take time to load.