How to set Image Cache Period on CachedNetworkImage in Flutter

In this example, we are going to show you how to set image cache time period on CachedNetworkImage of cached_network_image package or programmatically clear the specific cache file or all cache files. See the example:

You need to add flutter_cache_manager Flutter package as well in your project by adding following lines in your pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  cached_network_image: ^3.2.0
  flutter_cache_manager: ^3.3.0

cached_network_image comes with cacheManager as well, so you can use this package to manage it.

CachedNetworkImage(
    imageUrl: "https://www.fluttercampus.com/img/logo_small.webp",
    placeholder: (context, url) => CircularProgressIndicator(),
    errorWidget: (context, url, error) => Icon(Icons.error),
    cacheManager: CacheManager(
        Config(
          "fluttercampus",
          stalePeriod: const Duration(days: 7),
          //one week cache period
        )
    ),
)

Key is necessary to identity while managing it after caching.

await DefaultCacheManager().removeFile("fluttercampus");
//Cache with "fluttercampus" key will be removed.

await DefaultCacheManager().emptyCache();

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

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
         home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Image Cache Manager"),
            backgroundColor: Colors.redAccent
         ),
          body: Container(
             margin: EdgeInsets.all(30),
             alignment: Alignment.topCenter,
             child: Column(
                 children: [
                    CachedNetworkImage(
                        imageUrl: "https://www.fluttercampus.com/img/logo_small.webp",
                        placeholder: (context, url) => CircularProgressIndicator(),
                        errorWidget: (context, url, error) => Icon(Icons.error),
                        cacheManager: CacheManager(
                            Config(
                              "fluttercampus",
                              stalePeriod: const Duration(days: 7),
                              //one week cache period
                            )
                        ),
                    ),

                    Divider(),

                    ElevatedButton(
                      onPressed: () async {
                          await DefaultCacheManager().emptyCache();
                      }, 
                      child: Text("Clear All Image Cache")
                    ),

                    ElevatedButton(
                      onPressed: () async {
                         await DefaultCacheManager().removeFile("fluttercampus");
                          //Cache with "fluttercampus" key will be removed.
                      }, 
                      child: Text("Clear Only This Image")
                    )
                 ],
             ),
          )
    );
  } 
}

In this way, you can set the cache time period of images and clear cache on CachedNetworkImage of cached_network_image package in Flutter.

No any Comments on this Article


Please Wait...