saveRemember<T> method

Future<T> saveRemember<T>(
  1. String key,
  2. int seconds,
  3. dynamic callback()
)

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.

Implementation

Future<T> saveRemember<T>(
    String key, int seconds, Function() callback) async {
  final File cacheFile = File('${_cacheDirectory.path}/$key');
  if (await cacheFile.exists()) {
    final content = await cacheFile.readAsString();
    final data = jsonDecode(content);
    if (DateTime.now().isBefore(DateTime.parse(data['expiration']))) {
      return data['value'] as T;
    }
  }

  T value;
  if (callback is Future Function()) {
    value = await callback();
  } else {
    value = callback();
  }

  final expiration = DateTime.now().add(Duration(seconds: seconds));
  await cacheFile.writeAsString(jsonEncode({
    'value': value is Response ? value.toJson() : value,
    'expiration': expiration.toIso8601String(),
  }));
  return value;
}