saveForever<T> method

Future<T?> saveForever<T>(
  1. String key,
  2. FutureOr<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, FutureOr<T> Function() callback) async {
  if (!isAvailable) return await callback();

  final File cacheFile = _fileFor(key);
  if (await cacheFile.exists()) {
    try {
      final dynamic data = jsonDecode(await cacheFile.readAsString());
      return data['value'] as T?;
    } catch (_) {
      // Corrupted cache file, delete and continue to fetch fresh value
      await cacheFile.delete();
    }
  }

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