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.