cache method

void cache(
  1. String key,
  2. Object value, {
  3. Duration? cacheDuration,
})

Implementation

void cache(String key, Object value, {Duration? cacheDuration}) {
  if (cacheDuration == null) {
    // Null means "do not cache." Clear any prior entry under this key
    // so subsequent reads do not pick up a stale value.
    _evict(key);
    return;
  }
  // Clamp to at least 1 so a misconfigured `maxEntries <= 0` doesn't
  // evict every entry we just inserted.
  final effectiveCap = maxEntries < 1 ? 1 : maxEntries;
  // At capacity on a new-key insert, evict the oldest first.
  // Refreshing an existing key never grows the map.
  if (!_expirations.containsKey(key) && _expirations.length >= effectiveCap) {
    final overflow = _expirations.length - effectiveCap + 1;
    final toEvict = _expirations.keys.take(overflow).toList();
    for (final k in toEvict) {
      _evict(k);
    }
  }
  _inner.cache(key, value);
  _expirations[key] = DateTime.now().add(cacheDuration);
}