put method

  1. @override
Future<bool> put(
  1. String key,
  2. dynamic value, {
  3. Duration? ttl,
})
override

Stores a value in the cache with a unique identifier.

key - Unique identifier for the value value - Value to store (must be serializable for persistent cache) ttl - Time to live duration. If null, it doesn't expire automatically

Returns true if stored successfully, false otherwise

Implementation

@override
Future<bool> put(String key, dynamic value, {Duration? ttl}) async {
  try {
    final now = DateTime.now();
    final expiresAt = ttl != null ? now.add(ttl) : null;

    // Remove existing entry if present
    if (_cache.containsKey(key)) {
      _removeFromAccessTracking(key);
    }

    // Check if we need to evict entries to make space
    if (_maxSize != null &&
        _cache.length >= _maxSize! &&
        !_cache.containsKey(key)) {
      _evictToMakeSpace();
    }

    // Create new cache entry
    final entry = _CacheEntry(
      key: key,
      value: value,
      createdAt: now,
      lastAccessedAt: now,
      expiresAt: expiresAt,
      accessCount: 0,
    );

    // Store the entry
    _cache[key] = entry;

    // Update access tracking
    _updateAccessTracking(key, now);

    return true;
  } catch (e) {
    return false;
  }
}