get<T> method

Future<T?> get<T>(
  1. String key
)

Retrieves a value from the cache.

key is the unique identifier of the item to retrieve.

Returns the cached value if it exists and hasn't expired, null otherwise. If the item has expired, it is automatically removed from the cache. Returns null on web platform.

Implementation

Future<T?> get<T>(String key) async {
  if (!isAvailable) return null;

  final cacheFile = _fileFor(key);
  if (!await cacheFile.exists()) return null;

  try {
    final data = jsonDecode(await cacheFile.readAsString());
    final expirationStr = data['expiration'] as String?;
    if (expirationStr != null) {
      final expiration = DateTime.tryParse(expirationStr);
      if (expiration == null || DateTime.now().isAfter(expiration)) {
        await cacheFile.delete();
        return null;
      }
    }
    return data['value'] as T?;
  } catch (_) {
    // Corrupted cache file, delete it
    await cacheFile.delete();
    return null;
  }
}