ResultCache<K, V> class

An in-memory cache for Result values with optional TTL expiry.

Useful for caching successful API responses and serving them instantly on repeat calls without hitting the network:

final cache = ResultCache<String, User>(ttl: const Duration(minutes: 5));

Future<Result<User>> getUser(String id) =>
    cache.getOrFetch(id, () => api.fetchUser(id));

Only Success results are cached by getOrFetch; errors are always forwarded to the caller so they can retry immediately.

Constructors

ResultCache({Duration? ttl})
Creates a cache. Supply ttl to evict entries automatically after that duration; omit it for a cache that never expires.

Properties

hashCode int
The hash code for this object.
no setterinherited
keys Iterable<K>
An unmodifiable snapshot of the keys currently in the cache. Includes keys whose entries may have expired but have not yet been read (and thus not yet evicted). Useful for diagnostics and bulk invalidation.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
size int
The number of entries currently held. Includes entries that may have expired but have not yet been read (and thus not yet evicted).
no setter
ttl Duration?
Maximum age of a cache entry. null means entries never expire.
final

Methods

clear() → void
Removes all entries from the cache.
containsKey(K key) bool
Whether the cache contains a live (non-expired) entry for key.
get(K key) Result<V>?
Returns the cached Result for key, or null if the entry is absent or has expired. Expired entries are removed eagerly on read.
getOrFetch(K key, Future<Result<V>> fetch()) Future<Result<V>>
Returns the cached value for key if present and live; otherwise calls fetch, caches the result if it is a Success, and returns it.
invalidate(K key) → void
Removes the entry for key, if any.
invalidateWhere(bool test(K key)) int
Removes every entry whose K satisfies test. Returns the number of entries removed. Useful for tag-style invalidation when keys encode resource type or user scope (e.g. cache.invalidateWhere((k) => k.startsWith('user:'))).
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
put(K key, Result<V> value) → void
Stores value under key, overwriting any existing entry.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited