Back to Posts

How to Add List of Images in Flutter: Complete Guide

2 min read

Introduction

Displaying a list of images is a common requirement in many Flutter applications, whether for galleries, product listings, or other use cases. This guide will walk you through the process of adding and managing a list of images in Flutter, from asset declaration to efficient loading and display techniques.

Declaring Image Assets

To use images in your Flutter app, you first need to declare them in the pubspec.yaml file. Here's an example:

flutter:
  assets:
    - assets/images/image1.png
    - assets/images/image2.png
    - assets/images/image3.png

Ensure that the images are placed in the specified directory within your project structure.

Displaying a List of Images

You can use widgets like ListView or GridView to display a list of images. Below are examples of both approaches.

Using ListView

The ListView widget is ideal for displaying a vertical list of images.

ListView(
  children: [
    Image.asset('assets/images/image1.png'),
    Image.asset('assets/images/image2.png'),
    Image.asset('assets/images/image3.png'),
  ],
)

Using GridView

The GridView widget is perfect for creating a grid layout for images.

GridView.count(
  crossAxisCount: 2,
  children: [
    Image.asset('assets/images/image1.png'),
    Image.asset('assets/images/image2.png'),
    Image.asset('assets/images/image3.png'),
  ],
)

Loading Images Dynamically

If you have a large number of images, you can load them dynamically using a list of image paths.

final List<String> imagePaths = [
  'assets/images/image1.png',
  'assets/images/image2.png',
  'assets/images/image3.png',
];

ListView.builder(
  itemCount: imagePaths.length,
  itemBuilder: (context, index) {
    return Image.asset(imagePaths[index]);
  },
)

Optimizing Image Loading

To improve performance, consider the following optimization techniques:

  • Use CachedNetworkImage: For images loaded from the internet, use the cached_network_image package to cache images locally.
CachedNetworkImage(
  imageUrl: 'https://example.com/image.png',
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
)
  • Resize Images: Use the width and height properties to resize images and reduce memory usage.
Image.asset(
  'assets/images/image1.png',
  width: 100,
  height: 100,
)

Conclusion

Adding and managing a list of images in Flutter is straightforward with the tools and widgets provided by the framework. By following the techniques outlined in this guide, you can efficiently display images in your app while ensuring optimal performance. Experiment with different layouts and optimization strategies to create a seamless user experience.