Solved: Update Cached Image in Flutter

Question

Asked by Ananda P on January 03, 2022 (source).

I have a question, I am using cached_network_image package to cache image from network and my question is, can we update the cached image? Because if I update the image (URL stay the same), the app will show the old image instead of the new image and I need to clear the cache first to make the app show the latest image. Or is there expired time for the cached image? Thank you.

 CachedNetworkImage(
    imageUrl: dokter.foto,
    imageBuilder: (context, imageProvider) => CircleAvatar(backgroundImage: imageProvider),
    progressIndicatorBuilder: (context, url, downloadProgress) =>
       Center(
         child: CircularProgressIndicator(
              value: downloadProgress.progress,
              color : Constant.color
         ),
       ),
   errorWidget: (context, url, error) =>   Image.asset("assets/images/profileAvatar.png")
)

Answer

Question answered by Ramin (source).

According to this issue if the url is same it will take some time until it updates. I didn't see any expiration propery on the widget itself. Instead you can use a cacheKey to set for how long you want it to be valid. For example if it needs to remain valid only for a day you can use:

CachedNetworkImage(
      imageUrl: dokter.foto,
      cacheKey: dokter.foto + DateTime.now().day.toString(),
)

If it needs to be an hour or month it's pretty simple and you can just replace day with hour or month. Although for a certain number of days you might need to do some math. For 7 days you could simply do (DateTime.now().day / 7).floor(). Of course there are edge cases and depending on the time it was cached it might be valid only for an hour instead of 24 hours if you set it to day. But if you only need to set a maximum time for it to remain valid instead of letting the widget itself handle that, this is simple enough and should work fine.

UPDATE

Let's say you use (DateTime.now().hour to set maximum expiration time to 1 hour. At 9 AM user downloads and caches the first image. Before 10 AM a new image is uploaded. cacheKey changes at 10 AM so the new image is downloaded and cached. So far so good. The problem is the day after, from 9 to 10 AM your cacheKey will be used to retrieve the first image which is outdated. To solve this you can concat the day and hour together. But it's not clear how long cacheKeys are valid. So the same problem could happen after a week if the key remains valid for that long.

CachedNetworkImage.evictFromCache(url, cacheKey: cacheKey);

You can use this to remove the old cacheKey to prevent this.

Video Answers on YouTube

FLUTTER
SHARE: