put method

  1. @override
Future<void> put(
  1. String key,
  2. dynamic value,
  3. Duration ttl
)
override

Stores a value in the cache with a specified time-to-live (TTL).

The key is a unique identifier for the cached item. The value can be any dynamic type, and it will be stored for the duration specified by ttl. After the TTL expires, the item may be automatically removed from the cache.

Throws an exception if the key is null or empty, or if ttl is negative. Implementations should handle serialization of complex value types if needed.

  • Parameters:
    • key: A non-null, non-empty string representing the cache key.
    • value: The data to be cached, which can be of any type.
    • ttl: The duration for which the item should remain in the cache.

Implementation

@override
Future<void> put(String key, dynamic value, Duration ttl) async {
  if (key.isEmpty) {
    throw ArgumentError('Cache key cannot be empty');
  }

  if (ttl.isNegative) {
    throw ArgumentError('TTL duration cannot be negative');
  }

  final entry = _CacheEntry(
    value: value,
    expiresAt: DateTime.now().add(ttl),
    ttl: ttl,
  );

  _store[key] = entry;
  _stats.sets++;

  // Clean up expired entries during put operations
  _cleanupExpiredEntries();
}