How to Cache Images in Flutter?

Images are an essential part of modern apps. Since bandwidth is a costly commodity, caching of images can prevent the downloading of image every time the user views it on the screen. Caching will also improve the user experience when offline, by using the local cached copy without trying to download it again from the internet.

Here in this tutorial, we use cached_network_image package to cache and display network images. When the image is loaded for the first time the package caches it locally. The next time when the image is needed the packages fetches it locally rather than downloading it from internet.


Step 1

The first step is to include cached_network_image inside pubspec.yaml as shown below.

Step 2

This is a simple code snippet showing the implementation of cached_network_image. Here we make use of 3 arguments.

1. imageUrl - URL of image to be cached

2. placeholder - Placeholder Widget engages the space before the image is loaded

3. errorWidget - Error Widget will be displayed if there was an error downloading the image

Cached Image as the background of a Container

CachedNetworkImageProvider can be used to display the cached image as the background of a container as shown in the example above.