get method

Future<CachedData?> get(
  1. String key, {
  2. Map<String, dynamic> queryParams = const <String, dynamic>{},
  3. DateTime? updatedAt,
  4. bool removeSameKeyData = false,
  5. bool rebuildDb = false,
})

Get data from cache.

Provide the same key that you used when adding the data to retrieve data from cache. You can also use queryParams to specify the query parameters you used to fetch and cache the data. If you cached a data with both key and queryParams, you will need to provide both key and parameters to retrieve the data.

updatedAt can be used to indicate if the cache has outdated. If it is provided, then it will be used to compare with the datetime of the cached data to check if it has outdated. If the cache is outdated, it will be removed and null will be returned. If updatedAt is not provided, the data will always be retrieved from cache if it is still available.

When removing outdated cache, setting removeSameKeyData to true will remove all the data from cache with the same key, even they have different queryParams. And setting rebuildDb to true will clean up the SQL database and free up the space.

Implementation

Future<CachedData?> get(
  String key, {
  Map<String, dynamic> queryParams = const <String, dynamic>{},
  DateTime? updatedAt,
  bool removeSameKeyData = false,
  bool rebuildDb = false,
}) async {
  final params = QueryParams(queryParams);
  var data = await _getFromCache(key, params);

  if (updatedAt != null) {
    final cacheUpdatedAt = data?.updatedAt;
    if (cacheUpdatedAt != null && cacheUpdatedAt.isBefore(updatedAt)) {
      data = null;
      if (removeSameKeyData) {
        await removeByKey(key, rebuildDb: rebuildDb);
      } else {
        await remove(
          key,
          queryParams: queryParams,
          rebuildDb: rebuildDb,
        );
      }
    }
  }

  return data;
}