QueryClient class

The entry point of query_kit: owns the caches and everything imperative — fetching, reading and writing cached data, invalidating, cancelling.

A client holds a QueryCache (every query, keyed by QueryKey) and a MutationCache, the client-wide and per-key defaults, and three managers: focusManager and onlineManager, which tell it when the app returns to the foreground or the network comes back, and notifyManager, which batches listener notifications.

Lifetime. Create one client per app (or per test) and keep it for as long as the app runs — the cache lives in it, so a second client is a second, empty cache. Call mount once so it reacts to focus and connectivity (the Flutter binding's QueryClientProvider does this for you), and unmount and clear when you are done: a client owns gcTime timers that would otherwise keep a process or a test alive.

The most used members, grouped:

final client = QueryClient()..mount();
final todosKey = QueryKey(['todos']);

// Fetch once and cache; a second call within staleTime is served from
// the cache.
final todos = await client.query(QueryOptions<List<String>>(
  queryKey: todosKey,
  queryFn: (context) => api.fetchTodos(),
  staleTime: const StaleTime.duration(Duration(minutes: 1)),
));

// Write to the cache, e.g. after a mutation or optimistically.
client.setQueryData<List<String>>(todosKey, [...todos, 'Buy milk']);

// Mark stale and refetch everything under the key that is observed.
await client.invalidateQueries(filters: QueryFilters(queryKey: todosKey));

// When done (end of a test, a CLI's exit):
client.unmount();
client.clear();

Constructors

QueryClient({QueryCache? queryCache, MutationCache? mutationCache, DefaultOptions? defaultOptions, AppFocusManager? focusManager, OnlineManager? onlineManager, NotifyManager? notifyManager})
Creates a client. Every collaborator is optional: a fresh QueryCache, MutationCache, AppFocusManager, OnlineManager and NotifyManager are made when none is passed, and defaultOptions starts empty. Pass your own caches to install cache-wide callbacks (for example a global onError). Call mount to have it react to focus and connectivity, and clear when it is done — a client owns gcTime timers that outlive any widget tree.

Properties

focusManager → AppFocusManager
Whether the app is in the foreground. A mounted client refetches stale queries (per refetchOnWindowFocus) when it reports focus again. The Flutter binding drives it from the app lifecycle.
final
hashCode → int
The hash code for this object.
no setterinherited
mutationCache → MutationCache
Every mutation, in submission order. Subscribe to it for cache events.
final
notifyManager → NotifyManager
Batches this client's listener notifications. The Flutter binding installs a build-phase-aware scheduler on it; pass NotifyManager.shared to batch across clients.
final
onlineManager → OnlineManager
Whether the device is believed to be online. The Flutter binding drives its setOnline from an optional connectivity stream; a mounted client listens to it and resumes paused mutations and queries on reconnect.
final
queryCache → QueryCache
Every query, keyed by QueryKey. Subscribe to it for cache events; most reads and writes go through the client's own methods instead.
final
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

cancelQueries({QueryFilters filters = const QueryFilters(), bool revert = true, bool silent = false}) → Future<void>
Cancels every matching in-flight fetch, completing once they have all settled.
clear() → void
Empties both caches, cancelling in-flight fetches and every gcTime timer. This is the teardown call: a widget test ends with it, since Flutter's test binding asserts that no timer outlives the tree.
defaultMutationOptions<TData, TVariables, TOnMutateResult>(MutationOptions<TData, TVariables, TOnMutateResult> options) → DefaultedMutationOptions<TData, TVariables, TOnMutateResult>
Resolves mutation options against the key defaults, the client-wide defaults and the built-in defaults. Throws ArgumentError when both mutationFn and mutationFnWithContext are set.
defaultQueryObserverOptions<TQueryData, TData>(QueryObserverOptionsBase<TQueryData, TData> options) → DefaultedQueryObserverOptions<TQueryData, TData>
Resolves observer options against the key defaults, the client-wide defaults and the built-in defaults — the query half as defaultQueryOptions does, plus the observer-only fields (refetchOn*, refetchInterval, retryOnMount, …).
defaultQueryOptions<TQueryData>(QueryOptions<TQueryData> options) → DefaultedQueryOptions<TQueryData>
Resolves options against the key defaults, the client-wide defaults and the built-in defaults, filling in every field left null.
getDefaultOptions() → DefaultOptions
The client-wide defaults in force.
getInfiniteQueryData<TPageData, TPageParam>(QueryKey queryKey) → InfiniteData<TPageData, TPageParam>?
The cached infinite data under queryKey, or null if absent. Throws QueryDataTypeError when the entry has another data type.
getMutationDefaults(QueryKey mutationKey) → MutationDefaults?
The registered defaults matching mutationKey, merged in the order the keys were first registered, later ones winning per field — or null when none match. The mutation twin of getQueryDefaults.
getQueriesData<TQueryData>({required QueryFilters filters}) → List<(QueryKey, TQueryData?)>
The cached data of every matching query, null where a query holds none yet.
getQueryData<TQueryData>(QueryKey queryKey) → TQueryData?
The cached data under queryKey, or null if there is none.
getQueryDefaults(QueryKey queryKey) → QueryDefaults?
The registered defaults matching queryKey, merged in the order the keys were first registered — registering a key again replaces its defaults but keeps its place.
getQueryState<TQueryData>(QueryKey queryKey) → QueryState<TQueryData>?
The full state of the query under queryKey — status, fetch status, timestamps and counters, not just the data — or null if there is none. Throws QueryDataTypeError if the entry holds a different type.
infiniteObserverOptions<TPageData, TPageParam, TData>(InfiniteQueryObserverOptionsBase<TPageData, TPageParam, TData> options) → QueryObserverOptionsBase<InfiniteData<TPageData, TPageParam>, TData>
Resolves infinite-query options into the observer options a Query<InfiniteData<…>> runs on. The paging behaviour is the options' own (InfiniteQueryOptions.behavior); this only adds the observer half.
infiniteQuery<TPageData, TPageParam>(InfiniteQueryOptions<TPageData, TPageParam> options, {bool revalidateIfStale = false}) → Future<InfiniteData<TPageData, TPageParam>>
Fetches and caches an infinite query, completing with its pages.
invalidateQueries({QueryFilters filters = const QueryFilters(), RefetchType? refetchType, bool cancelRefetch = true}) → Future<void>
Marks matching queries stale and refetches the ones refetchType names, which defaults to the filter's own type and then to QueryTypeFilter.active — the queries an observer is watching. Queries nobody watches are only marked, and refetch when next observed.
isFetching({QueryFilters filters = const QueryFilters()}) → int
How many queries matching filters are fetching right now — actually fetching, not paused. Every query when the filters are empty.
isMutating({MutationFilters filters = const MutationFilters()}) → int
How many mutations matching filters are pending right now. Every mutation when the filters are empty. The count always looks at pending mutations: a MutationFilters.status passed here is ignored rather than combined.
mount() → void
Starts listening for focus and connectivity changes.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
observe<TQueryData, TData>(QueryObserverOptionsBase<TQueryData, TData> options) → QueryObserver<TQueryData, TData>
Creates a QueryObserver for options on this client — the same as QueryObserver(client, options).
observeInfinite<TPageData, TPageParam, TData>(InfiniteQueryObserverOptionsBase<TPageData, TPageParam, TData> options) → InfiniteQueryObserver<TPageData, TPageParam, TData>
A one-off infinite observer for options — the twin of observe, as infiniteQuery is of query. The caller owns its lifetime.
query<TQueryData>(QueryOptions<TQueryData> options, {bool revalidateIfStale = false}) → Future<TQueryData>
Fetches and caches options's query, completing with its data.
refetchQueries({QueryFilters filters = const QueryFilters(), bool cancelRefetch = true}) → Future<void>
Refetches every query matching filters — all of them when the filters are empty — whether stale or not.
removeQueries({QueryFilters filters = const QueryFilters()}) → void
Removes every query matching filters from the cache — all of them when the filters are empty — cancelling their fetches silently.
resetQueries({QueryFilters filters = const QueryFilters(), bool cancelRefetch = true}) → Future<void>
Puts matching queries back to the state they were created with, then refetches the active ones.
resumePausedMutations() → Future<void>
Resumes every paused mutation that can run right now, completing once they have all settled.
setDefaultOptions(DefaultOptions options) → void
Replaces the client-wide defaults. Takes effect wherever options are resolved next — a new observer, an observer's next setOptions, or a client call such as query. Options already resolved, such as those a query holds, are not changed.
setMutationDefaults(QueryKey mutationKey, MutationDefaults defaults) → void
Defaults for every mutation whose key starts with mutationKey; the mutation twin of setQueryDefaults. A second registration under the same key replaces the first.
setQueryData<TQueryData>(QueryKey queryKey, TQueryData data, {DateTime? updatedAt}) → TQueryData
Writes data into the cache, creating the entry if needed.
setQueryDefaults(QueryKey queryKey, QueryDefaults defaults) → void
Defaults for every query whose key starts with queryKey.
toString() → String
A string representation of this object.
inherited
unmount() → void
Stops listening for focus and connectivity changes.
updateQueriesData<TQueryData>(TQueryData? updater(TQueryData? previous), {required QueryFilters filters, DateTime? updatedAt}) → List<(QueryKey, TQueryData?)>
Runs updater over every query matching filters and returns each key with what it now holds. A type mismatch anywhere under the filters throws before anything is written. The filtered twin of updateQueryData (TanStack Query's setQueriesData), and as lenient: a matching entry takes any value its own type can hold.
updateQueryData<TQueryData>(QueryKey queryKey, TQueryData? updater(TQueryData? previous), {DateTime? updatedAt}) → TQueryData?
Updates the cached data under queryKey from what it holds now.

Operators

operator ==(Object other) → bool
The equality operator.
inherited