Flutter: Caching Network Images for Big Performance gains

Last updated on August 27, 2021 A Goodman Loading... 2 comments

The goodness of caching network images in a Flutter application does more than just boot up the performance of the application itself. Other significant benefits are:

  • Reduce the burden on your server and reduce the cost you have to pay for bandwidth in loading images.
  • Reduce internet charges for your users if they use 3G/4G.

Fortunately, implementing image caching in Flutter is not an advanced task and we can get it done with a few dozen lines of code and the help of a great plugin named cached_network_image.

Overview

1. The cached_network_image plugin provides a widget named CachedNetworkImage that shows a network image with caching functionality. The image displayed with this widget will be downloaded and stored in the cache directory of the app for a period of time. It will available for offline use without an internet connection.

You can implement the widget as shown below:

CachedNetworkImage(
              width: double.infinity,
              height: 250,
              fit: BoxFit.cover,
              imageUrl: [image url],
              progressIndicatorBuilder: (context, url, downloadProgress) =>
                  CircularProgressIndicator(value: downloadProgress.progress),
              errorWidget: (context, url, error) => Icon(
                Icons.error,
                size: 100,
                color: Colors.red,
              ),
),

2. To delete the cached image, you can call the CachedNetworkImage.evictFromCache static method:

CachedNetworkImage.evictFromCache([image url])

Example

App Preview

The demo app we are going to build contains 2 images and a button. The first image will be cached and the second one won’t. Here’s how it works:

  1. At the beginning, both images are loaded correctly because my wifi is on.
  2. When I turn off my internet connection and restart the app, the first image is still fine but the the second one goes into error.
  3. When I press the button Remove Cached Images and restart the app, the first image will be replaced by an error icon. This behavior makes sense because the cached file is now gone.
  4. I enable my wifi again and restart the app. Everything is fine again.

The Code

1. Install the cached_network_image plugin by running:

flutter pub add cached_network_image

2. The final code in lib/main.dart with explanations:

// main.dart
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
          primarySwatch: Colors.green,
        ),
        home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // This image will be cached
  final _image1 =
      'https://www.kindacode.com/wp-content/uploads/2021/08/face.png';

  // This image will not be cached
  // It is added to show the difference
  final _image2 =
      'https://www.kindacode.com/wp-content/uploads/2021/08/cat.jpeg';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Display image with caching
            Text('Caching'),
            SizedBox(
              height: 10,
            ),
            CachedNetworkImage(
              width: double.infinity,
              height: 250,
              fit: BoxFit.cover,
              imageUrl: _image1,
              progressIndicatorBuilder: (context, url, downloadProgress) =>
                  CircularProgressIndicator(value: downloadProgress.progress),
              errorWidget: (context, url, error) => Icon(
                Icons.error,
                size: 100,
                color: Colors.red,
              ),
            ),
            SizedBox(
              height: 10,
            ),
            // This button is used to remove the saved image from the cache directory
            ElevatedButton(
                onPressed: () {
                  CachedNetworkImage.evictFromCache(_image1);
                },
                child: Text('Remove Cached Images')),

            SizedBox(
              height: 10,
            ),
            // Display image without caching
            Divider(),
            Text('Non Caching:'),
            SizedBox(
              height: 10,
            ),
            Image.network(
              _image2,
              width: double.infinity,
              height: 200,
              fit: BoxFit.cover,
            )
          ],
        ),
      ),
    );
  }
}

Conclusion

We’ve examined a complete example of implementing image caching in a mobile application. This functionality provides a bunch of benefits at a low cost of time and effort. If you’d like to explore more new and interesting stuff in Flutter development, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
BBi
BBi
15 days ago

How long have image catch on store?
I research and see cached_network_image follow flutter_cache_manager. Default for 7 days? Do it right? And can you have the example to config this duration? Thank you

Related Articles