json_cache

Json Cache 是一个面向对象的包,作为本地存储包(在用户设备上本地持久化数据的包)之上的一层,将它们统一为一个优雅的缓存 API。

此外,这个包为程序员提供了极大的灵活性;它提供了一组可以以各种方式选择和组合的类,以满足特定的缓存需求。

为什么是 Json?

  • 因为 Flutter 应用程序可用的大多数本地存储包
    都使用 json 作为数据格式。
  • Dart 内置类型
    Map<String, dynamic> 和 json 之间存在一对一的关系,这使得 json 编码/解码成为一项
    微不足道的工作。

入门

JsonCache——这个包的核心接口——代表了
缓存数据的概念。它定义为

/// Represents a cached json data.
abstract class JsonCache {
  /// Frees up cache storage space.
  Future<void> clear();

  /// Refreshes some cached data by its associated key.
  Future<void> refresh(String key, Map<String, dynamic> data);

  /// Erases [key] and returns its associated data.
  Future<Map<String, dynamic>?> erase(String key);

  /// Recovers some cached data; null if a cache miss occurs - no [key] found.
  Future<Map<String, dynamic>?> recover(String key);
}

将每个缓存条目(键/数据对)视为一组
相关数据是合理的。因此,期望将用户数据分组缓存,其中键
代表单个数据组的名称。例如

'profile': {'name': 'John Doe', 'email': '[email protected]', 'accountType': 'premium'};
'preferences': {'theme': {'dark': true}, 'notifications':{'enabled': true}}

上面的 'profile' 键与配置文件相关数据组相关联;
'preferences',与偏好数据相关。

GitHub

https://github.com/dartoos-dev/json_cache