cacheData static method

Future<void> cacheData(
  1. String cacheKey,
  2. List data, {
  3. Duration? duration,
  4. Map<String, dynamic>? metadata,
})

Saves data to the cache

Implementation

static Future<void> cacheData(
  String cacheKey,
  List<dynamic> data, {
  Duration? duration,
  Map<String, dynamic>? metadata,
}) async {
  await init();

  try {
    final cacheData = {
      'data': data,
      'timestamp': DateTime.now().millisecondsSinceEpoch,
      'duration':
          duration?.inMilliseconds ?? _defaultCacheDuration.inMilliseconds,
      'metadata': metadata ?? {},
    };

    final jsonString = jsonEncode(cacheData);
    await _prefs!.setString('$_cachePrefix$cacheKey', jsonString);

    await _updateCacheMetadata(cacheKey, cacheData);

    // Drop old cache entries if needed
    await _cleanupOldCache();
  } catch (e) {
    throw Exception('Error while saving to the cache: $e');
  }
}