getCache method

Future getCache({
  1. required String key,
  2. bool allowExpired = false,
})

Read cached value for key.

Freshness:

  • If a ttl was stored and it has expired, returns null unless allowExpired is true.
  • If ttl was null at write-time, the entry is treated as non-expiring (always fresh).

Returns the parsed JSON if possible; otherwise returns the raw string.

Implementation

Future<dynamic> getCache({
  required String key,
  bool allowExpired = false,
}) async {
  final String? jsonStr = await _localStorageManager.getString(key: key);
  if (jsonStr == null) return null;

  final Map<String, dynamic> decoded = jsonDecode(jsonStr);
  final int? savedAt = decoded['savedAt'];
  final int? ttl = decoded['ttl'];

  // Respect TTL when present. If ttl is null, the entry is non-expiring.
  if (!allowExpired && savedAt != null && ttl != null) {
    final int now = DateTime.now().millisecondsSinceEpoch;
    if (now - savedAt > ttl) return null;
  }

  final dynamic raw = decoded['value'];
  if (raw is! String) return raw;

  try {
    final dynamic parsed = jsonDecode(raw);
    return parsed;
  } catch (_) {
    return raw;
  }
}