ifNotCached<T> method

Future<T?> ifNotCached<T>(
  1. String key,
  2. Future<T?> compute(), {
  3. Map<String, dynamic>? metadata,
})

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;
}