getCachedData static method

Future<CacheResult?> getCachedData(
  1. String cacheKey
)

Reads data from the cache

Implementation

static Future<CacheResult?> getCachedData(String cacheKey) async {
  await init();

  try {
    final jsonString = _prefs!.getString('$_cachePrefix$cacheKey');
    if (jsonString == null) return null;

    final cacheData = jsonDecode(jsonString) as Map<String, dynamic>;
    final timestamp = cacheData['timestamp'] as int;
    final duration = cacheData['duration'] as int;
    final data = cacheData['data'] as List<dynamic>;
    final metadata = cacheData['metadata'] as Map<String, dynamic>? ?? {};

    final now = DateTime.now().millisecondsSinceEpoch;
    if (now - timestamp > duration) {
      // Expired cache, remove it
      await removeCachedData(cacheKey);
      return null;
    }

    return CacheResult(
      data: data,
      timestamp: DateTime.fromMillisecondsSinceEpoch(timestamp),
      metadata: metadata,
      isExpired: false,
    );
  } catch (e) {
    // On error, remove the corrupted cache
    await removeCachedData(cacheKey);
    return null;
  }
}