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);
Installation
Add to pubspec.yaml:
Find the most recent version on pub.
Usage
A cache can be created from a simple manually controlled cache and composed with automatic
functionalities. Such as dependencies and time to live.
Creating a cache:
A simple cache is only invalidated manually.
Accessing value
when the cache is invalid refreshes the cache. It can be refreshed manually via
the refresh
method:
Composing a cache
A cache can be composed with more resources via a declarative API. By doing that, it is possible to
add TTL and dependency without diverging from the original behavior of a cache.
Example:
You can even create your behavior yourself by extending SingleChildCachedValue
.
Adding dependency
A dependent cache is marked as invalid if its dependency value has changed.
⚠️Important:
The dependency callback is called on every value access. So it is recommended to keep it as declarative as possible.
Adding time to live
A cache can be automatically marked as invalid some time after a refresh.
More docs
There is more detailed docs on the API documentation.
Motivation
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.
Example on a render object:
Can be changed to: