How to preload images with cached_network_image?

Viewed 3718

I've just implemented the Flutter package cached_network_image and I wonder how I can preload images so they're available later in an instant. I retrieve all image-urls that will be used later from the our server.

I've defined my custom cache manager getter:

class LocalCacheManager {
  static const key = 'customCacheKey';
  static CacheManager instance = CacheManager(
    Config(
      key,
      stalePeriod: const Duration(days: 14),
      maxNrOfCacheObjects: 200,
      repo: JsonCacheInfoRepository(databaseName: key),
      fileSystem: LocalCacheFileSystem(key),
      fileService: HttpFileService(),
    ),
  );
}

Here's how I currently try to preload the image:

LocalCacheManager.instance.downloadFile(MY_IMAGE_URL)),

And here's how I create the widget:

child: CachedNetworkImage(imageUrl: MY_IMAGE_URL, cacheManager: LocalCacheManager.instance),

But I can clearly see that files are always cached again as soon as I create the CachedNetworkImage.

3 Answers

You can use Flutter Cache Manager like this

DefaultCacheManager().downloadFile(MY_IMAGE_URL).then((_) {});

Later, just use your cached image like this

child: CachedNetworkImage(imageUrl: MY_IMAGE_URL,),

Simplest and workable way is to use precacheImage (flutter build-in function) with CachedNetworkImageProvider:

Image image = Image(
        image: CachedNetworkImageProvider(/* url */),
        fit: BoxFit.cover,
      );

      precacheImage(image.image, context);

      return Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8.0),
                child: image,
              ),
            );
 cached_network_image: ^2.0.0 
            CachedNetworkImage(
                      imageUrl: yoururl,
                      errorWidget: (context, url, error) => Text("error"),
                      imageBuilder: (context, imageProvider) => CircleAvatar(
                        radius: 120,
                        backgroundImage: imageProvider,
                      ),
                      placeholder: (context, url) => CircularProgressIndicator(
                        backgroundColor: primary,
                      ),
                    ),
Related