Uraam Asif
Uraam Asif

Reputation: 63

Flutter: How to extend the age of the cached image

I am working on an application that involves a lot of image caching, to reduce database costs. I am using Cached_network_image with Flutter_Cache_Manager.

My usage :

SizedBox(
  width: 75,
  height: 75,
  child: AspectRatio(
    aspectRatio: 16/13,
    child: Container(
      decoration: BoxDecoration(
        color: colorProvider.fourthColor,
        borderRadius: BorderRadius.circular(5),
      ),
      clipBehavior: Clip.hardEdge,
      child: query["thumbnail"].trim().isNotEmpty ? CachedNetworkImage(
        imageUrl: query["thumbnail"].trim(),
        fit: BoxFit.cover,
        cacheManager: CacheManager(
          Config(
            '${query["thumbnail"].trim()}',
            stalePeriod: const Duration(hours: 36),
          ),
        ),
        fadeInDuration: const Duration(milliseconds: 10),
        errorWidget: (context, url, error) => Center(
          child: Icon(Icons.error, size: 24, color: colorProvider.secondText),
        ),
      ) : Center(child: Icon(Icons.error, size: 24, color: colorProvider.secondText,),),
    ),
  ),
),

Here I am caching the image for 36 hours, and after 36 hours, the image is removed from the cache. But, I want to extend the stalePeriod to 36 hours whenever a user views the image.

For example, if an image is cached and an hour has remained before it's removed from the cache. If the user views it again, I want to change the cached image's live time from an hour back to 36 hours.

Every bit of help would be much appreciated, for this is very crucial to my app.

Upvotes: 0

Views: 216

Answers (1)

myyvee
myyvee

Reputation: 95

Directly modifying the existing cached image's expiration time is not possible in most caching libraries. One idea would be to recach the image with all network costs. Another idea could be to implement a custom invalidation mechanism within your caching library. This could involve: Storing an additional metadata field with the cached image indicating its original expiration time. When the image is viewed, update the metadata field with the new expiration time (36 hours from the current time). During cache cleanup, check the metadata field and only remove images that have exceeded their original expiration time, not the updated one. This approach requires modifying the caching library or implementing a custom caching solution, which can be more complex. Good Luck.

Upvotes: 0

Related Questions