Syncache<T> class
An offline-first cache and sync engine for Dart applications.
Syncache provides a unified API for caching data with multiple strategies, reactive updates via streams, and optimistic mutations with automatic background sync.
Basic Usage
// Create a cache instance
final cache = Syncache<User>(
store: MemoryStore<User>(),
);
// Fetch data with offline-first policy
final user = await cache.get(
key: 'user:123',
fetch: (request) => api.getUser(123),
);
// Watch for reactive updates
cache.watch(
key: 'user:123',
fetch: (request) => api.getUser(123),
).listen((user) {
print('User updated: ${user.name}');
});
Caching Policies
Control caching behavior with Policy:
- Policy.offlineFirst: Cache first, fetch if expired (default)
- Policy.cacheOnly: Only use cached data
- Policy.networkOnly: Always fetch from network
- Policy.refresh: Fetch if online, cache if offline
- Policy.staleWhileRefresh: Return cache, refresh in background
Optimistic Mutations
await cache.mutate(
key: 'user:123',
mutation: Mutation<User>(
apply: (user) => user.copyWith(name: 'New Name'),
send: (user) => api.updateUser(user),
),
);
Network Awareness
Provide a custom Network implementation for offline detection:
final cache = Syncache<User>(
store: MemoryStore<User>(),
network: MyConnectivityNetwork(),
);
See also:
- Store for storage backend options
- Policy for caching strategies
- Mutation for optimistic updates
- SyncacheObserver for monitoring cache operations
- Available extensions
Constructors
-
Syncache({required Store<
T> store, Network? network, List<SyncacheObserver> ? observers, RetryConfig? defaultRetry, MutationRetryConfig? mutationRetry}) -
Creates a Syncache instance with the given
storeand optionalnetwork.
Properties
- defaultRetry → RetryConfig
-
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- hasPendingMutations → bool
-
Returns whether there are any pending mutations.
no setter
-
isSyncedStream
→ Stream<
bool> -
Stream that emits true when all mutations are synced.
no setter
- mutationRetry → MutationRetryConfig
-
final
- network → Network
-
final
-
observers
→ List<
SyncacheObserver> -
final
- pendingMutationCount → int
-
Returns the number of pending mutations.
no setter
-
pendingMutationsSnapshot
→ List<
PendingMutationInfo> -
Returns a snapshot of current pending mutations.
no setter
-
pendingMutationsStream
→ Stream<
List< PendingMutationInfo> > -
Stream of pending mutation info for UI sync indicators.
no setter
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
-
store
→ Store<
T> -
final
Methods
-
clear(
) → Future< void> - Clears all cached entries.
-
clearPendingMutations(
) → void - Removes all pending mutations from the sync queue.
-
clearScope(
String scope) → Future< void> - Clears all cached entries within a scope.
-
dispose(
) → void - Disposes of this Syncache instance and releases all resources.
-
get(
{required String key, required Fetcher< T> fetch, Policy policy = Policy.offlineFirst, Duration? ttl, RetryConfig? retry, CancellationToken? cancel, List<String> ? tags}) → Future<T> -
Retrieves a value from the cache or network based on the
policy. -
getConditional(
{required String key, required ConditionalFetcher< T> fetch, Policy policy = Policy.offlineFirst, Duration? ttl, RetryConfig? retry, CancellationToken? cancel}) → Future<T> - Retrieves a value using a ConditionalFetcher that supports HTTP 304.
-
getWithMeta(
{required String key, required Fetcher< T> fetch, Policy policy = Policy.offlineFirst, Duration? ttl, RetryConfig? retry, CancellationToken? cancel}) → Future<CacheResult< T> > - Retrieves a value with cache metadata.
-
invalidate(
String key) → Future< void> -
Invalidates (deletes) the cached entry for the given
key. -
invalidateInScope(
String scope, String pattern) → Future< void> - Invalidates entries within a scope matching a pattern.
-
invalidatePattern(
String pattern) → Future< void> -
Invalidates all cache entries whose keys match the given glob
pattern. -
invalidateTag(
String tag) → Future< void> -
Invalidates all cache entries with the specified
tag. -
invalidateTags(
List< String> tags, {bool matchAll = false}) → Future<void> -
Invalidates all cache entries that have any of the specified
tags. -
mutate(
{required String key, required Mutation< T> mutation, List<String> ? invalidates, List<String> ? invalidateTags}) → Future<void> - Applies an optimistic mutation to a cached value.
-
mutateList(
{required String key, required ListOperation< T> operation, required Future<void> send(), List<String> ? invalidates, List<String> ? invalidateTags}) → Future<void> -
Available on Syncache<
Mutates a cached list with a specific operation.List< , provided by the SyncacheListExtension extensionT> > -
mutateListItem<
Id> ({required String key, required ListOperation< T> operation, required Future<T> send(T item), required Id idSelector(T item), List<String> ? invalidates, List<String> ? invalidateTags}) → Future<void> -
Available on Syncache<
Mutates a cached list with server response updating the item.List< , provided by the SyncacheListExtension extensionT> > -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
prefetch(
List< PrefetchRequest< requests) → Future<T> >List< PrefetchResult> > - Prefetches multiple cache entries in parallel.
-
prefetchGraph(
List< PrefetchNode< nodes, {PrefetchGraphOptions options = PrefetchGraphOptions.defaults}) → Future<T> >PrefetchGraphResult> - Prefetches multiple cache entries with dependency ordering.
-
prefetchOne(
{required String key, required Fetcher< T> fetch, Duration? ttl, Policy policy = Policy.refresh, RetryConfig? retry}) → Future<bool> - Prefetches a single cache entry. Returns true on success.
-
removeFirstPendingMutation(
) → bool - Removes the first pending mutation from the sync queue.
-
scoped(
String scope) → ScopedSyncache< T> - Creates a scoped view of this cache.
-
set(
{required String key, required T value, Duration? ttl}) → Future< void> - Sets a value directly in the cache without fetching.
-
toString(
) → String -
A string representation of this object.
inherited
-
watch(
{required String key, required Fetcher< T> fetch, Policy policy = Policy.offlineFirst, Duration? ttl}) → Stream<T> -
Returns a reactive stream of values for the given
key. -
watchWithDependencies(
{required String key, required Fetcher< T> fetch, required List<String> refetchWhen, Policy policy = Policy.offlineFirst, Duration? ttl}) → Stream<T> - Returns a reactive stream that automatically refetches when dependencies change.
-
watchWithMeta(
{required String key, required Fetcher< T> fetch, Policy policy = Policy.offlineFirst, Duration? ttl}) → Stream<CacheResult< T> > -
Returns a reactive stream of values with metadata for the given
key.
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited