• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by User Bot


26 Mar, 2025

Updated at 20 May, 2025

Flutter's CachedNetworkImage doesn't seem to clean up data from temporary storage

thanks for taking the time to help!

I am building an app that displays many images/GIFs. I have been using CachedNetworkImage to display these assets. I noticed today that my app cache on both iOS and Android were larger than expected (500MB on iOS and 1GB on Android).

I did some investigating and found that there were thousands of cached GIFs/jpgs under libCachedImageData and that many of the files haven't been accessed for over 30 days.

I was under the assumption that CachedNetworkImage's default cache only keeps things around for 30 days and up to 200MB. Am I missing a step to make sure the cache is properly cleaned up?

Thank you!

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:tabler_icons/tabler_icons.dart';

class OptimizedCachedImage extends StatelessWidget {
  final String imageUrl;
  final double? width;
  final double? height;
  final BoxFit? fit;
  final Widget Function(BuildContext, String)? placeholder;
  final Widget Function(BuildContext, String, Object)? errorWidget;
  final ProgressIndicatorBuilder? progressIndicatorBuilder;

  const OptimizedCachedImage({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.fit,
    this.placeholder,
    this.errorWidget,
    this.progressIndicatorBuilder,
  });

  @override
  Widget build(BuildContext context) {
    final pixelRatio = MediaQuery.of(context).devicePixelRatio;
    final finalWidth = width != null ? width! * pixelRatio : null;
    final finalHeight = height != null ? height! * pixelRatio : null;

    return CachedNetworkImage(
      cacheKey: '$imageUrl-${finalWidth?.round()}x${finalHeight?.round()}',
      imageUrl: imageUrl,
      width: width,
      height: height,
      fit: fit,
      memCacheWidth: finalWidth?.round(),
      memCacheHeight: finalHeight?.round(),
      maxWidthDiskCache: finalWidth?.round(),
      maxHeightDiskCache: finalHeight?.round(),
      placeholder: placeholder,
      errorWidget: errorWidget ??
          (context, url, error) => const Icon(TablerIcons.file_broken),
      progressIndicatorBuilder: progressIndicatorBuilder,
    );
  }
}