put method
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 {
await _ensureInitialized();
try {
final now = DateTime.now();
final expiresAt = ttl != null ? now.add(ttl) : null;
// Check if we need to evict entries to make space
if (_maxSize != null &&
_metadataCache.length >= _maxSize! &&
!_metadataCache.containsKey(key)) {
await _evictToMakeSpace();
}
// Serialize value
final serializedValue = _serializeValue(value);
if (serializedValue == null) return false;
// Create metadata entry
final metadata = _PersistentCacheEntry(
key: key,
createdAt: now,
lastAccessedAt: now,
expiresAt: expiresAt,
accessCount: 0,
sizeInBytes: _estimateSize(value),
dataType: _getDataType(value),
);
// Store value and metadata
await _prefs!.setString('$_keyPrefix$key', serializedValue);
await _prefs!.setString('$_metadataPrefix$key', metadata.toJson());
// Update in-memory metadata cache
_metadataCache[key] = metadata;
return true;
} catch (e) {
return false;
}
}