json_cache 0.1.0 json_cache: ^0.1.0 copied to clipboard
An object-oriented package for caching user data locally in json; a combinable layer on top of local storage packages that unifies them as an elegant caching API.
json_cache #
Contents #
Overview #
Json Cache is an object-oriented package to cache user data locally in json. It can also be thought of as a layer on top of Flutter's local storage packages like sharable_preferences and local storage that unifies them as an elegant caching API.
Why Json?
- Because most of the local storage packages available for Flutter applications use json as the data format.
- There is a one-to-one relationship between Dart's built-in type
Map<String, dynamic>
and json, which makes encoding/decoding data in json a trivial task.
Getting Started #
This package gives developers great flexibility by providing a set of classes that can be selected and grouped in various combinations to meet specific cache requirements.
JsonCache
is the core interface of this package and represents the concept of
cached data. It is defined as:
/// Represents data cached in json.
abstract class JsonCache {
/// Frees up storage space.
Future<void> clear();
/// Updates data at [key] or creates a new cache line at [key] if there is no
/// previous data there.
Future<void> refresh(String key, Map<String, dynamic> data);
/// Removes data from cache at [key] and returns it or returns null if there
/// is no data at [key].
Future<Map<String, dynamic>?> erase(String key);
/// Retrieves either the data at [key] or null if a cache miss occurs.
Future<Map<String, dynamic>?> recover(String key);
}
It is reasonable to consider each cache entry (a key/data pair) as a group of related data. Thus, it is expected to cache data into groups, where a key represents the name of a single data group. For example:
'profile': {'name': 'John Doe', 'email': 'johndoe@email.com', 'accountType': 'premium'};
'preferences': {'theme': {'dark': true}, 'notifications':{'enabled': true}}
Above, the profile key is associated with the profile-related data group, while the preferences key is associated with the preferences-related data.
Demo application #
The demo application provides a fully working example, focused on demonstrating the caching API in action. You can take the code in this demo and experiment with it.
To run the demo application:
git clone https://github.com/dartoos-dev/json_cache.git
cd json_cache/example/
flutter run -d chrome
This should launch the demo application on Chrome in debug mode.