cached_value 是一个轻量级的 Flutter/Dart 包,提供了一种简单的方式来缓存由昂贵操作派生的值。它确保一旦值被计算,就会被存储并重复使用,而无需重新计算,从而提高性能并降低延迟。该包支持异步操作,并可配置过期时间自动处理缓存。适用于 API 响应、复杂计算或数据解析等场景,避免重复计算。
适合场景
缓存 API 响应
存储计算结果
减少冗余数据处理
提高应用程序的响应速度
管理昂贵的初始化任务
保留临时状态
主要特点
简单的异步缓存
可配置的过期时间
到期后自动重新计算
支持空安全值
轻量且依赖极少
跨平台兼容性
适合对象
寻求简单缓存的开发者
频繁进行昂贵计算的应用程序
性能优化项目
带有缓存数据的状态管理
快速缓存解决方案原型设计
使用建议
不适用于大型数据集
没有内置的跨应用重启持久化
在某些情况下需要手动清除缓存
限制为内存存储
最适合短暂缓存的值
不支持复杂的缓存策略
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
cached_value
A simple way to cache values that result from rather expensive operations.
It is useful to cache values that:
Are computed from other values in a consistent way;
Can be changed given known and unknown conditions;
Should not be computed on every access (like a getter);
A cached_value is better used over imperative APIs, such as Flutter's render objects. See Motivation for more.
Installation
Add to pubspec.yaml:
dartpubaddcached_value
Usage
A cache can start as a simple manually controlled cache and then be enhanced with automatic functionalities such as dependencies and time-to-live (TTL).
1.Creating a simple cached that is invaldiated manually
intfactorial(int n) {
if (n < 0) throw ('Negative numbers are not allowed.');
return n <= 1 ? 1 : n * factorial(n - 1);
}
int originalValue = 1;
final factorialCache = CachedValue(() => factorial(originalValue));
print(factorialCache.value); // 1
originalValue = 6;
print(factorialCache.value); // 1print(factorialCache.isValid) // true, invalid only when invalidate is called// mark as invalid
factorialCache.invalidate();
print(factorialCache.isValid); // falseprint(factorialCache.value); // 720print(factorialCache.isValid); // true
Accessing value when the cache is invalid refreshes the cache. It can be refreshed manually via
the refresh method:
Some imperative APIs such as the canvas paint on Flutter render objects of Flame's components may
benefit from values that can be stored and reused between more than a single frame (or paint).
In some very specific cases, I found very convenient to store some objects across frames, like
Paint and TextPainter instances.