Flutter Tricks
Published on

How to Show and Cache Images from the Network

When building Flutter applications, it is common to need to display images fetched from the network. To enhance the performance and user experience, it is important to efficiently handle image loading and caching. In this article, we will explore how to achieve this using the cached_network_image package.

Installing the Package

Before we get started, make sure you have the cached_network_image package installed in your Flutter project. To do so, open your terminal and run the following command:

flutter pub add cached_network_image

Once the installation is complete, you can import the package in your Dart files using:

import 'package:cached_network_image/cached_network_image.dart';

Showing Images from the Network

To display an image from the network using the cached_network_image package, you can use the CachedNetworkImage widget. This widget takes in the URL of the image as a parameter and automatically handles loading and caching.

Here's an example of how to use the CachedNetworkImage widget:

CachedNetworkImage(
  imageUrl: 'https://example.com/image.jpg',
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
),

In the example above, we provide the imageUrl parameter with the URL of the image we want to display. We also specify a placeholder widget to show while the image is being loaded, and an errorWidget to display in case the image fails to load.

By using the CachedNetworkImage widget, the package takes care of loading the image from the network and caching it for future use. This helps in reducing network requests and improving the app's performance.

Summary

In this article, we learned how to efficiently show and cache images from the network in Flutter using the cached_network_image package. We explored how to display images using the CachedNetworkImage widget. By following these practices, you can enhance the user experience and reduce unnecessary network requests in your Flutter applications.