23

i dont want to store image in cache.. iam using CachedNetworkImage for image loading.. I want know is there any option to remove or do not store image in cache like picasso..

my code:

var annotatedImg = CachedNetworkImage(
      fit: BoxFit.fill,
      imageUrl: Constants.IMAGE_BASE_URL + widget._fileId + Constants.CONTOUR_IMG_SUFFIX,
      placeholder: (context, url) => progressBar,
      errorWidget: (context, url, error) => new Icon(Icons.error),
    );

i have tried

annotatedImg.cacheManager.emptyCache();

but its shows cant call emptyCache is null..

1
  • 1
    It is so frustrated that there is no info nor code just to delete or replace the freaking one cache file I really need to do :/ Commented Jul 25, 2021 at 11:55

10 Answers 10

33

Since CachedNetworkImage version 2.3, all these solutions won't work because it cached images in 2 different places (DefaultCacheManager & NetworkImageProvider)

So the only solution is using the evictFromCache built-in method from CachedNetworkImage

like this:

Future _deleteImageFromCache() async {
    String url = "your url";
    await CachedNetworkImage.evictFromCache(url);
  }

evictFromCache is a Static method so it doesn't require to have the CachedNetworkImage in your Widget tree, you can use it directly from any place.

Sign up to request clarification or add additional context in comments.

1 Comment

where to call this method
24

I agree with MichaelM, Don't use CachedNetworkImage.If you show image like this :

Image.network(
      _headImageUrl,
      fit: BoxFit.fitHeight,
    )

you can use those code to clean image cache:

PaintingBinding.instance.imageCache.clear();

2 Comments

Thank you so much for this answer. I was struggling for three months with images that I deleted but they kept appearing on the screen. I was so frustrated because that didn't make any sense to me. After I saw your answer, I added PaintingBinding.instance.imageCache.clear() after I deleted the images and it finally worked. Again, thank you so much man, this really helped me.
This clears the entire image cache. Better just remove the one image provider like this: _imgProvider = NetworkImage(url); _imgProvider.evict(); Be sure to evict it from cache before loading the image.
24

Firstly add the package (flutter_cache_manager) to pubspec.yaml file as following:

dependencies: flutter: sdk: flutter flutter_cache_manager: ^1.1.3

After a day, I found the solution. Use the DefaultCacheManager object by calling emptyCache() method, this clears the cache data.

DefaultCacheManager manager = new DefaultCacheManager();
manager.emptyCache(); //clears all data in cache.

Comments

14

import 'package:flutter_cache_manager/flutter_cache_manager.dart'; await DefaultCacheManager().removeFile('YOUR_URL');

DONT USE emptyCache() from the first answer, it clear ALL your Cache

2 Comments

It doesn't clear cache if the app isn't restarted. Any way to solve that too ?
@SteevJames for me it works without restarting the application!
4

CachedNetworkImage stores the images in temporary(cache) folder, you can get access to it with path_provider's getTemporaryDirectory() method. There you will find libCachedImageData (You might need to check the name). There you can delete the folder.

To do it in your app you should use Directory class like:

final Directory tempDir = await getTemporaryDirectory();
final Directory libCacheDir = new Directory("${tempDir.path}/libCachedImageData");
await libCacheDir.delete(recursive: true);

Comments

2

If you do not want to store the downloaded image in a cache, then don't use CachedNetworkImage. Instead, use a FadeInImage widget with a NetworkImage:

FadeInImage(
  // here `bytes` is a Uint8List containing the bytes for the in-memory image
  placeholder: // This should be an image, so you can't use progressbar,
  image: NetworkImage('https://backend.example.com/image.png'),
)

1 Comment

i want to progress bar in placeholder
1

In your CachedNetworkImage, add CacheManager Config:

CachedNetworkImage(CacheManager(Config(
              featureStoreKey,
              stalePeriod: const Duration(seconds: 15),
              maxNrOfCacheObjects: 1,
              repo: JsonCacheInfoRepository(databaseName: featureStoreKey),
              fileService: HttpFileService(),
            ),
        ),
  fit: BoxFit.fill,
  imageUrl: Constants.IMAGE_BASE_URL + widget._fileId + Constants.CONTOUR_IMG_SUFFIX,
  placeholder: (context, url) => progressBar,
  errorWidget: (context, url, error) => new Icon(Icons.error),
);

Then to clear it, add this void statement:

void _clearCache() {
try {
  JsonCacheInfoRepository(databaseName: featureMain1Store).deleteDataFile();
} catch (e, s) {
  print(s);
}
imageCache!.clear();
imageCache!.clearLiveImages();
setState(() {});
}

Comments

1

I wanted to test my widget that uses CachedNetworkWidget, but without using the existing cache.

Adding CachedNetworkImage.evictFromCache in the imageBuilder did the job:

 return CachedNetworkImage(
    imageUrl: widget.item.img_url,
    imageBuilder: (context, imageProvider) {
      if (kDebugMode) CachedNetworkImage.evictFromCache(widget.item.img_url);

      //...rest of the code
    },
  );

Comments

0

1- for CachedNetworkImage library

`CachedNetworkImage(
    imageUrl: "https://www.fluttercampus.com/img/logo_small.webp",
    placeholder: (context, url) => CircularProgressIndicator(),
    errorWidget: (context, url, error) => Icon(Icons.error),
    cacheManager: CacheManager(
        Config(
          "fluttercampus",
          stalePeriod: const Duration(days: 7),
          //one week cache period
        )
    ),
)`

you can use one of those

await DefaultCacheManager().removeFile("fluttercampus");

await CachedNetworkImage.evictFromCache('YOUR_URL');

don't use this cause it will delete all data in CacheManager

await DefaultCacheManager().emptyCache();

2- if you want to delete from Image.network use this

Image.network(
      _headImageUrl,
      fit: BoxFit.fitHeight,
    )

you can use those code to clean image cache:

PaintingBinding.instance.imageCache.clear();

Comments

0

In my project, I had to add this feature in the debug menu to give QAs an option to clear cached images.

So earlier, because of this cached_network_image: ^3.3.1 dependency flutter_cache_manager was coming transitively.

However to achieve explicit cache cleanup, we need to add this in pubspec.yaml

flutter_cache_manager: ^3.3.2

Now you get access to DefaultCacheManager and cache can be evicted using below await DefaultCacheManager().emptyCache(); Optionally below line of code will clean up flutter memory cache.

// Clears memory cache
  PaintingBinding.instance.imageCache.clear();
  PaintingBinding.instance.imageCache.clearLiveImages();

Sample code to trigger the cache cleanup on button click

`TextButton(
                onPressed: () async {
                  await DefaultCacheManager().emptyCache();
                  // Clears memory cache
                  PaintingBinding.instance.imageCache.clear();
                  PaintingBinding.instance.imageCache.clearLiveImages();
                  if (context.mounted) {
                    ScaffoldMessenger.of(context)
                      ..clearSnackBars()
                      ..showSnackBar(const SnackBar(content: Text('Image cache cleared')));
                  }
                },
                child: const Text('Clear Image Cache', textAlign: TextAlign.center),
              ),`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.