ifNotCached<T> method
Get cached value or compute and cache if missing.
If key exists in cache, returns cached value.
If key doesn't exist, calls compute, caches the result, and returns it.
Example:
final user = await cache.ifNotCached(
'user:123',
() => api.fetchUser(123),
metadata: {'ttl_seconds': 3600},
);
Implementation
Future<T?> ifNotCached<T>(
String key,
Future<T?> Function() compute, {
Map<String, dynamic>? metadata,
}) async {
final cached = await get(key, metadata: metadata);
if (cached != null) {
return cached as T;
}
final computed = await compute();
if (computed != null) {
await put(key, computed, metadata: metadata);
}
return computed;
}