fetchDataWithCaching<T> function

Future<T> fetchDataWithCaching<T>(
  1. Future<T> fetchData(),
  2. String cacheKey,
  3. Duration cacheDuration, {
  4. bool forceRefresh = false,
})

Implementation

Future<T> fetchDataWithCaching<T>(
  Future<T> Function() fetchData,
  String cacheKey,
  Duration cacheDuration, {
  bool forceRefresh = false,
}) async {
  final encryptionKey = await getEncryptionKey();
  final box = await Hive.openBox<CachedResponse<T>>(
    CACHING_BOX,
    encryptionCipher: HiveAesCipher(encryptionKey),
  );

  // Check if cached data is available and not expired
  final cachedResponse = box.get(cacheKey);

  if (!forceRefresh &&
      cachedResponse != null &&
      DateTime.now().difference(DateTime.parse(cachedResponse.timestamp)) <
          cacheDuration) {
    return cachedResponse.data;
  }

  // Fetch data from the API
  final data = await fetchData();

  // Cache the fetched data
  await box.put(
    cacheKey,
    CachedResponse<T>(data: data, timestamp: DateTime.now().toIso8601String()),
  );

  return data;
}