PersistQoraClient class
A QoraClient that automatically persists query results to a StorageAdapter and restores them on startup (offline-first).
Quick start
// 1. Create with a storage backend (swap InMemory for Hive/Isar/etc.)
final storage = InMemoryStorageAdapter();
final client = PersistQoraClient(
storage: storage,
persistDuration: Duration(days: 7),
);
// 2. Register a serializer for every type you want to persist.
// Pass `name:` explicitly when targeting Flutter Web or --obfuscate.
client.registerSerializer<User>(
QoraSerializer(toJson: (u) => u.toJson(), fromJson: User.fromJson),
name: 'User',
);
client.registerSerializer<List<Post>>(
QoraSerializer(
toJson: (posts) => posts.map((p) => p.toJson()).toList(),
fromJson: (json) => (json as List).map((e) => Post.fromJson(e)).toList(),
),
name: 'List<Post>',
);
// 3. Warm the cache from disk before the first widget builds.
await storage.init();
await client.hydrate();
runApp(QoraScope(client: client, child: const MyApp()));
Auto-persist
After every successful fetch for a type that has a registered serializer,
the result is written to StorageAdapter as a JSON string containing the
serialised data, a type discriminator (typeName), and TTL metadata.
Both direct fetches and SWR background revalidations are persisted because
both paths go through QoraClient._doFetch, which calls onFetchSuccess.
Hydration
hydrate reads all stored entries, evaluates TTL, deserializes valid
entries using the registered serializers, and calls queueHydration on
the base QoraClient. The actual injection into the typed cache happens
lazily on the first typed API call (fetchQuery, watchQuery, etc.)
to avoid Dart runtime cast failures (see QoraClient._applyPendingHydration).
The restored Success state carries the original persistedAt timestamp
as updatedAt, so QoraOptions.staleTime works correctly: if the data is
older than staleTime, the first watchQuery mount triggers a SWR
background revalidation automatically.
Mutation queue
Registered mutations queued with offlineQueue: true are stored in the
same StorageAdapter, one entry per call, before they count as queued.
hydrate restores them after the cache, and clearStorage deletes
them. See MutationQueue.
Storage eviction
| Method | In-memory cache | StorageAdapter |
|---|---|---|
| invalidate | Marks stale | Untouched |
| removeQuery | Removed | Deleted |
| clear | Cleared | Cleared |
| clearStorage | Untouched | Cleared |
| evictFromStorage | Untouched | Deleted |
Name-based registration (obfuscation-safe)
// Without name: uses T.toString(), unsafe on Flutter Web / --obfuscate
client.registerSerializer<User>(serializer);
// With explicit name: always stable
client.registerSerializer<User>(serializer, name: 'User');
- Inheritance
-
- Object
- QoraClient
- PersistQoraClient
Constructors
- PersistQoraClient({required StorageAdapter storage, Duration? persistDuration = const Duration(days: 7), QoraClientConfig? config, QoraTracker? tracker})
- Creates a PersistQoraClient.
Properties
-
activeMutations
→ Map<
String, MutationUpdate> -
Snapshot of all currently running (pending) mutations, keyed by
controller ID.
no setterinherited
-
cachedKeys
→ Iterable<
List> -
All currently cached query keys (normalised).
no setterinherited
- config → QoraClientConfig
-
Global configuration for this client instance.
finalinherited
-
fetchingCountStream
→ Stream<
int> -
Stream that emits the total number of in-flight query requests each time
the count changes.
no setterinherited
- hashCode → int
-
The hash code for this object.
no setterinherited
- isFetchingCount → int
-
The number of query requests currently in flight.
no setterinherited
- isOnline → bool
-
truewhen a ConnectivityManager is attached and reports online status, or when no manager is configured (assumed online by default).no setterinherited -
mutationEvents
→ Stream<
MutationUpdate> -
Real-time stream of all mutation state changes from tracked
MutationControllers.
no setterinherited
- mutationQueue → MutationQueue
-
The queue of registered mutations.
no setterinherited
- mutationRegistry → MutationRegistry
-
The mutations registered on this client, by key.
no setterinherited
- networkStatus → NetworkStatus
-
The current network status as reported by the attached
ConnectivityManager.
no setterinherited
- offlineMutationQueue → OfflineMutationQueue
-
The shared queue for mutations enqueued while offline.
no setterinherited
- pendingOfflineMutations → List
-
A snapshot of all mutations currently waiting in the offline queue.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
attachConnectivityManager(
ConnectivityManager manager) → void -
Attaches a ConnectivityManager and begins listening to network status
changes.
inherited
-
attachLifecycleManager(
LifecycleManager manager) → void -
Attaches a LifecycleManager and wires
refetchOnWindowFocusbehaviour.inherited -
clear(
) → void -
Remove all cached queries and cancel all pending requests.
override
-
clearCache(
) → void -
Clear the in-memory cache only. Persisted storage is untouched.
Use clear to wipe both (if using persistence), or clearStorage
to wipe storage only.
inherited
-
clearHydrationQueue(
) → void -
Remove all pending hydration entries.
inherited
-
clearStorage(
) → Future< void> - Delete every entry Qora wrote to StorageAdapter without clearing the in-memory cache.
-
debugInfo(
) → Map< String, dynamic> -
Returns a debug snapshot of the current cache and mutation state.
inherited
-
debugSetQueryError(
Object key, Object error) → void -
Forces the cached entry for
keyinto a Failure state witherror.inherited -
dispose(
) → void -
Release all resources held by this client.
inherited
-
evictFromStorage(
Object key) → Future< void> -
Delete the persisted entry for
keyfrom StorageAdapter only. -
fetchQuery<
T> ({required Object key, required Future< T> fetcher(), QoraOptions? options, CancelToken? cancelToken}) → Future<T> -
Fetch data once and return the result.
inherited
-
getInfiniteQueryData<
TData, TPageParam> (Object key) → InfiniteData< TData, TPageParam> ? -
Returns the loaded InfiniteData for
key, ornullwhen no pages have been fetched yet.inherited -
getInfiniteQueryState<
TData, TPageParam> (Object key) → InfiniteQueryState< TData, TPageParam> -
Returns the current InfiniteQueryState for
key, or InfiniteInitial if no entry exists yet.inherited -
getQueryData<
T> (Object key) → T? -
Returns the cached data for
key, ornullif unavailable.inherited -
getQueryState<
T> (Object key) → QoraState< T> -
Returns the full QoraState for
key, or Initial if not cached.inherited -
hasActiveWatcher(
Object key) → bool -
Returns
truewhenkeyhas at least one active watchQuery subscriber.inherited -
hydrate(
) → Future< void> - Load all valid persisted entries from StorageAdapter into the base QoraClient's pending hydration queue, ready to be injected into the typed cache on the first access.
-
hydrateQuery<
T> (Object key, T data, {DateTime? updatedAt}) → void -
Pre-populate the cache with a previously persisted value.
inherited
-
invalidate(
Object key) → void -
Mark a query as stale and cancel any in-flight request for it.
inherited
-
invalidateInfiniteQuery(
Object key) → void -
Reset an infinite query to InfiniteInitial, signalling observers to
re-fetch from the first page.
inherited
-
invalidatePrefix(
Object prefix) → void -
Invalidate every query whose key starts with
prefix.inherited -
invalidateQueries(
{required QueryFilter filter}) → void -
Invalidate all queries matching
filter.inherited -
invalidateTags(
List< QueryTag> tags) → Future<void> -
Invalidate all queries that provide any of the given
tags.inherited -
invalidateWhere(
bool predicate(List key)) → void -
Invalidate all queries whose normalised keys satisfy
predicate.inherited -
markStale(
Object key) → void -
Marks the query for
keyas stale without notifying active observers.inherited -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
onFetchSuccess<
T> (List key, T data) → void -
Extension point for subclasses. Called synchronously after every
successful fetch inside
_doFetch: covering both direct fetches and SWR background revalidations.override -
persistQuery<
T> (Object key, {Duration? ttl}) → Future< void> -
Force-persist the current cached value for
keyto StorageAdapter. -
prefetch<
T> ({required Object key, required Future< T> fetcher(), QoraOptions? options, CancelToken? cancelToken}) → Future<void> -
Pre-warm the cache without creating a stream or blocking the caller's UI.
inherited
-
prepopulateCache<
T> (Object key, QoraOptions options) → void -
Eagerly seeds the cache with QoraOptions.initialData or
QoraOptions.placeholderData before any fetch is triggered.
inherited
-
queueHydration(
Object key, dynamic data, {DateTime? updatedAt}) → void -
Enqueue a pre-deserialized value to be injected into the typed cache on
the first typed API call (fetchQuery, watchQuery, etc.) for
key.inherited -
registerMutation<
TData, TVariables> (String key, {required RegisteredMutator< TData, TVariables> mutator, required QoraSerializer<TVariables> variables, List<Object> ? invalidates, List<QueryTag> ? invalidatesTags, String? scope(TVariables variables)?, bool isPermanent(Object error)?}) → void -
Registers a mutation under
key, so call sites can run it withMutationOptions(mutationKey: key)instead of passing a mutator.inherited -
registerSerializer<
T> (QoraSerializer< T> serializer, {String? name}) → void -
Register a QoraSerializer for type
T. -
removeHydrationEntry(
Object key) → void -
Remove the pending hydration entry for
keywithout injecting it.inherited -
removeQuery(
Object key) → void -
Remove a single query from cache and cancel any pending requests for it.
override
-
restoreQueryData<
T> (Object key, T? snapshot) → void -
Restore query data from a previous snapshot (optimistic rollback).
inherited
-
setInfiniteQueryData<
TData, TPageParam> (Object key, InfiniteData< TData, TPageParam> data, {bool? hasNextPage, bool? hasPreviousPage}) → void -
Directly replace the loaded data for an infinite query.
inherited
-
setQueryData<
T> (Object key, T data) → void -
Manually set query data in the cache, instantly pushing the new
Success state to all active watchQuery streams.
inherited
-
setTracker(
QoraTracker tracker) → void -
Replaces the active tracker with
tracker.inherited -
toString(
) → String -
A string representation of this object.
inherited
-
trackMutation<
TData, TVariables> (String id, MutationState< TData, TVariables> state, {Map<String, Object?> ? metadata}) → void -
Called on every state transition of a MutationController.
inherited
-
untrackMutation(
String id) → void -
Called when a MutationController is disposed.
inherited
-
updateInfiniteQueryState<
TData, TPageParam> (Object key, InfiniteQueryState< TData, TPageParam> state) → void -
Push a new InfiniteQueryState for
keyto all active subscribers.inherited -
watchFetchStatus(
Object key) → Stream< FetchStatus> -
Returns a stream of FetchStatus changes for
key.inherited -
watchInfiniteState<
TData, TPageParam> (Object key) → Stream< InfiniteQueryState< TData, TPageParam> > -
Observe the InfiniteQueryState for an infinite query by
key.inherited -
watchQuery<
T> ({required Object key, required Future< T> fetcher(), QoraOptions? options, CancelToken? cancelToken}) → Stream<QoraState< T> > -
Create a reactive Stream of QoraState for a query.
inherited
-
watchState<
T> (Object key) → Stream< QoraState< T> > -
Subscribe to the QoraState stream of a query without triggering a
fetch.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited