4

I have been trying to add a cache for images in flutter, but I haven't been able to set the cache duration.

I have tried using the cached_network_image package, where I have a custom cache manager where I overwrite the cache duration to 2 minutes (instead of having it as the default, which is 30 days), but the images are being cached for more then 2 minutes, it is even still being cached 1 day later).

When I simply use the Image.network component, the images are not being cached.

My custom cache manager:

class ImageCacheManager extends BaseCacheManager {
  static const key = "libCachedImageData";

  static ImageCacheManager _instance;

  factory ImageCacheManager() {
    if (_instance == null) {
      _instance = new ImageCacheManager._();
    }
    return _instance;
  }

  ImageCacheManager._() : super(key, maxAgeCacheObject: Duration(minutes: 2));

  Future<String> getFilePath() async {
    var directory = await getTemporaryDirectory();
    return p.join(directory.path, key);
  }
}

expected: the images will not be cached longer than I specify (e.g. 2 minutes)

actual: the images are cached for longer time than I specify (at least 36 hours)

2 Answers2

1

I've recently faced a similar problem when I wanted to change the maxAge of a resource to be cached. Thing is, internally the cache_manager takes the cache-control response header with a max-age value into consideration for setting the cache age. And if the resource doesn't return a max-age response header, it sets it to 7 days by default and we don't have a configuration for it. For a hack, we can set the response header within the customHttpGetter method we link to the custom cache manager and let the cache use it for caching. I've tried doing that and it works great!

https://referbruv.com/blog/posts/caching-get-request-calls-using-flutter-cache-manager

ram
  • 21
  • 5
0

If you have control of the server from where the images are coming, you can set the cache-control header yourself. For example, in nginx you can add a location block to the sites-available config file:

location ~* \.(?:png|jpg)$ {
    expires 2m;
    add_header Cache-Control "public";
}

This sets all png and jpg files to have a cache expiration of 2 minutes.

See also:

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393