saveRemember<T> method
Saves a value in the cache with an expiration time.
key is the unique identifier for the cached item.
seconds is the number of seconds until the item expires.
callback is a function that returns the value to be cached.
Returns the cached value, either from the cache if it exists and hasn't expired, or by calling the callback function and caching the result. Returns null on web platform where caching is not available.
Implementation
Future<T?> saveRemember<T>(
String key,
int seconds,
FutureOr<T> Function() callback,
) async {
if (!isAvailable) return await callback();
final cacheFile = _fileFor(key);
if (await cacheFile.exists()) {
try {
final data = jsonDecode(await cacheFile.readAsString());
final expiration = DateTime.tryParse(data['expiration'] ?? '');
if (expiration != null && DateTime.now().isBefore(expiration)) {
return data['value'] as T?;
}
} catch (_) {
// Corrupted cache file, delete and continue to fetch fresh value
await cacheFile.delete();
}
}
final value = await callback();
await cacheFile.writeAsString(
jsonEncode({
'value': _serialize(value),
'expiration': DateTime.now()
.add(Duration(seconds: seconds))
.toIso8601String(),
}),
);
return value;
}