clear method

  1. @override
Future<void> clear()
override

Clears all items from the cache.

Removes all cached data, effectively resetting the cache to an empty state. This operation is irreversible and should be used with caution.

Implementations may throw exceptions if the clear operation fails due to underlying storage issues (e.g., disk errors).

Implementation

@override
Future<void> clear() async {
  final dir = Directory(_cacheDir);

  if (!await dir.exists()) {
    return;
  }

  final lockFile = await _acquireClearLock();
  try {
    await for (final entity in dir.list()) {
      if (entity is File &&
          entity.path.endsWith(_fileExtension) &&
          !entity.path.endsWith(_metadataFile)) {
        await _deleteFileBestEffort(entity);
      }
    }

    // Reset statistics
    _stats.reset();
    _stats.clears = 1;
    await _saveMetadata();
  } catch (e) {
    // If directory listing fails, try to recreate the directory
    try {
      await dir.delete(recursive: true);
      await dir.create(recursive: true);
      _stats.reset();
      _stats.clears = 1;
      await _saveMetadata();
    } catch (e) {
      // If all else fails, just reset stats
      _stats.reset();
    }
  } finally {
    try {
      if (await lockFile.exists()) {
        await lockFile.delete();
      }
    } catch (_) {
      // Ignore lock cleanup failures.
    }
  }
}