evictExpired method

  1. @override
void evictExpired()
override

Removes all expired entries from the cache.

This is useful for periodic cleanup in long-running applications. Some implementations may call this automatically during get/set operations.

Implementation

@override
void evictExpired() {
  final expiredKeys = <String>[];

  for (final key in _storageBox.keys) {
    final json = _storageBox.get(key);
    if (json == null) continue;

    try {
      final entry = CacheEntry.fromJson(Map<String, dynamic>.from(json));
      if (entry.isExpired) {
        expiredKeys.add(key.toString());
      }
    } on Exception catch (e, s) {
      log(
        'HiveCacheStore: Failed to deserialize cache entry for key "$key": $e',
        level: 900,
        stackTrace: s,
      );
      // Mark corrupted entries for deletion
      expiredKeys.add(key.toString());
    }
  }

  expiredKeys.forEach(delete);
}