saveForever<T> method

Future<T> saveForever<T>(
  1. String key,
  2. Future<T> callback()
)

Saves a value in the cache without an expiration time.

key is the unique identifier for the cached item. callback is a function that returns the value to be cached.

Returns the cached value, either from the cache if it exists, or by calling the callback function and caching the result.

Implementation

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

  final T value = await callback();
  await cacheFile.writeAsString(jsonEncode({
    'value': value,
  }));
  return value;
}