clear method
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;
}
// Don't use locking for clear operation as it's too complex.
// WARNING: Without locking, concurrent cache operations (e.g., put/get/forget) during clear()
// may result in race conditions or inconsistent cache state. For single-threaded or
// single-process usage, this is generally safe, but in multi-isolate or multi-process scenarios,
// external synchronization should be considered.
try {
await for (final entity in dir.list()) {
if (entity is File &&
entity.path.endsWith(_fileExtension) &&
!entity.path.endsWith(_metadataFile)) {
try {
await entity.delete();
} catch (e) {
// Continue with other files if one fails
}
}
}
// Reset statistics
_stats.reset();
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();
await _saveMetadata();
} catch (e) {
// If all else fails, just reset stats
_stats.reset();
}
}
}