Dynamic S3 Bucket URL Caching Flutter

Viewed 629

I would like to cache a Network Image from an S3 bucket URL against an id or key. I tried to use the key: parameter but it didn't work. Please advise how I can achieve this. Heres the Cached Network Image code with the 'key' parameter that doesn't seem to do what I intend.

       CachedNetworkImage(
           key: Key(uni['university_name'].toString()), // Doesn't seem to do the job
            imageUrl: uni['image_url'],
            placeholder: (context, url) => CardPlaceHolder(),
            errorWidget: (context, url, error) => Padding(
              padding: EdgeInsets.all(21),
              child: Icon(
                Icons.error,
                size: 30,
                color: Colors.red.withOpacity(0.8),
              ),
            ),
            imageBuilder: (context, imageProvider) => ...
2 Answers

cached_network_image has been updated to handle keys with the cacheKey value. Check out the code below:

CachedNetworkImage(
  cacheKey: "my-key",
  imageUrl: _url!,
  fit: BoxFit.cover,
  progressIndicatorBuilder:
      (context, url, downloadProgress) =>
          Center(
    child: Platform.isAndroid
        ? CircularProgressIndicator()
        : CupertinoActivityIndicator(),
  ),
)

Currently CachedNetworkImage lack cached image retrival by key

Key you used is Widgets key, not related with CachedNetworkImage behavior

Let see what is in inside of CachedNetworkImage

cached_network_image depends on flutter_cache_manager

And flutter_cache_manager has implementation (issue #179) of retrival by key but it still not released in any version

So CachedNetworkImage will miss this functionality till flutter_cache_manager version has released it new versions

Though we can use this functionality, but we need to implement widget from our side

Temporary solution

  1. depend on flutter_cache_manager
/// this is pubspec dependencies:
flutter_cache_manager:
    git:
      url: https://github.com/Baseflow/flutter_cache_manager
      path: flutter_cache_manager
      ref: f109a48c31c4b3ed0a2c1ea2a5749c495e4fa2f4
  1. evolve this naive implementaion to match your use case
    FutureBuilder<File>(
      future: DefaultCacheManager().getSingleFile(
          'url', key: 'file-id'),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Image.file(snapshot.data);
        }
        // implement here some behavior like CachedNetworkImage does
        return CircularProgressIndicator();
      },
    );

PS I'll update answer when CachedNetworkImage will support

Related