cleanupOldCache static method

Future<void> cleanupOldCache([
  1. Duration maxAge = maxCacheAge
])

Removes old cached images that exceed maxAge.

This is useful for periodic cleanup without deleting all cached images.

Example:

// Remove images older than 7 days
await NotificationImageLoader.cleanupOldCache(Duration(days: 7));

Implementation

static Future<void> cleanupOldCache([Duration maxAge = maxCacheAge]) async {
  if (kIsWeb) return;

  try {
    final cacheDir = await _getCacheDirectory();
    if (!await cacheDir.exists()) return;

    final files = await cacheDir.list().toList();
    final now = DateTime.now();
    int deletedCount = 0;

    for (final entity in files) {
      if (entity is File) {
        final stat = await entity.stat();
        final age = now.difference(stat.modified);

        if (age > maxAge) {
          await entity.delete();
          deletedCount++;
        }
      }
    }

    if (deletedCount > 0) {
      logi('Cleaned up $deletedCount old notification images');
    }
  } catch (e, stackTrace) {
    loge(e, 'Error cleaning up old notification images', stackTrace);
  }
}