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.

Implementation

Future<T?> get<T>(String key) async {
  final File cacheFile = File('${_cacheDirectory.path}/$key');
  if (await cacheFile.exists()) {
    final content = await cacheFile.readAsString();
    final data = jsonDecode(content);
    if (data.containsKey('expiration')) {
      if (DateTime.now().isBefore(DateTime.parse(data['expiration']))) {
        return data['value'] as T?;
      } else {
        await cacheFile.delete();
        return null;
      }
    }
    return data['value'] as T?;
  }
  return null;
}