资源库
用于 Flutter 应用数据管理的资源/存储库模式实现。
入门
- 添加依赖
flutter pub add resource_repository - Package 默认使用
SimpleMemoryCacheStorage。您可以添加其他的- Hive resource_repository_hive。推荐用于小数据。
- ObjectBox resource_repository_objectbox。在大数据集上更有效。
用法
存储库可以是“远程”或“本地”的。本地应用于管理本地数据,例如,当您需要比简单的键值存储更多的东西时,可以替代 shared_preferences。远程应提供一个 FetchData 回调来从外部加载数据,例如 REST API 调用。
final localRepository = StreamRepository.local({
CacheStorage<K, V>? storage, // pass any of the implementations of CacheStorage
});
final remoteRepository = StreamRepository.remote({
required FetchData<K, V> fetch,
CacheStorage<K, V>? storage, // SimpleMemoryCacheStorage will be used if null
Duration? cacheDuration, // Pass duration value or duration resolver for complex logic.
CacheDurationResolver<K, V>? cacheDurationResolver,
});
然后您可以订阅资源,观察所有资源或使用存储库的其他功能。
final repository = StreamRepository<String, FooBar>.remote(
fetch: (key, arguments) => apiCall(fooBarId: key),
cacheDuration: const Duration(minutes: 30),
storage: SimpleMemoryCacheStorage('foobar_storage_key'),
);
repository.stream('1234').listen((fooBar) {
// work with resource
});
// Do something
repository.invalidate('1234'); // reload
附加信息
如果您创建了新的 CacheStorage 实现,请在项目的 github 页面上告知我。我会将其添加到自述文件中。