Caching duration in Flutter using the plugin cached_network_image?

338

CachedNetworkImage can receive a parameter called cacheManager. That means that you can give a custom CacheManager to your CachedNetworkImage First of all you should add this package to your pubspec.yaml. Then you can add something like this:

CachedNetworkImage(
  imageUrl: snapshot.data,
  cacheManager: CacheManager(
    Config(
      'cacheKey',
      stalePeriod: Duration(days: 7),
    ),
  ),
),

Replace the duration with your wanted duration and the cache key with any String you want. Add other parameters to the Config object if needed.

Just to note, the duration of the cache is 7 days (in this example) from the last use of the cached file, not from the download date.

Share:
338
Ayrix
Author by

Ayrix

Updated on November 23, 2022

Comments

  • Ayrix
    Ayrix over 1 year

    I'm using the flutter plugin cached_network_image: and would like to know, how long the caching duration is for the cached files? Also if there is a way to modify the caching duration to x-days?

    What I also would like to know is, if the files are cached in the original file format or if it gets converted? e.g. *.HEIC -> *.JPEG

    Currently I'm simply caching calling: CachedNetworkImage(imageUrl: snapshot.data))

    or see below....

    ...return FutureBuilder(
                          future: FireStorageService.downloadImageFromStorage(
                              context, snapshot.data.items[index].fullPath),
                          builder: (context, snapshot) {
                            if (snapshot.connectionState == ConnectionState.done) {
                              return GridTile(
                                child: Card(
                                    child: CachedNetworkImage(imageUrl: snapshot.data)),
                              );
                            }
                            return Container();
                          },
                        );
    ...
    

    While searching for an answer regarding my questions above, I got faced with the plugin flutter_cache_manager: and saw the Type Duration(days: 7)

    If this (using flutter_cache_manage:) is the only way to modify the caching duration, how can I use that in my case?

    Anyone has an idea?

    Thanks :)

  • Ayrix
    Ayrix almost 3 years
    Thanks for the detailed information - it works perfect :)