get method
Get data from cache or fetch fresh Key can be a String or Map<String, dynamic (like React Query) Users must handle serialization/deserialization themselves
Implementation
Future<dynamic> get(
dynamic key,
Future<dynamic> Function() fetcher, {
Duration? ttl,
}) async {
final normalizedKey = _normalizeKey(key);
final entry = _metadata[normalizedKey];
// Cache hit - return if not expired
if (entry != null && !_isExpired(entry)) {
// Update access metadata
final updatedEntry = entry.copyWith(
lastAccessTime: DateTime.now(),
accessCount: entry.accessCount + 1,
);
_metadata[normalizedKey] = updatedEntry;
await storage.write(normalizedKey, jsonEncode(updatedEntry.toJson()));
// Return cached data directly (user handles deserialization)
return entry.data;
}
// Cache miss - fetch fresh data
final freshData = await fetcher();
await set(key, freshData, ttl: ttl);
return freshData;
}