query_kit library

Asynchronous state management for Dart: fetching, caching, refetching, invalidation and mutations of server data — a port of TanStack Query's query-core that runs anywhere Dart runs, no Flutter needed.

query_kit is an entirely AI-coded project: all code, tests and documentation were written by AI coding agents (Anthropic's Claude). A human maintainer set the goals and reviews releases, but did not write the code.

query_kit is an independent community port and is not affiliated with or endorsed by TanStack. For Flutter widgets on top of it, see the query_kit_flutter package.

Quick start

A QueryClient owns the cache. Describe a query with QueryOptions — a QueryKey that identifies it and a query function that fetches it — then fetch it imperatively with QueryClient.query, or follow it with a QueryObserver, which fetches on subscribe, refetches when the data is stale and something happens (focus, reconnect, invalidation), and reports every change as a sealed QueryResult.

import 'package:query_kit/query_kit.dart';

Future<void> main() async {
  final client = QueryClient()..mount();
  final todosKey = QueryKey(['todos']);

  // Fetch once and cache.
  final todos = await client.query(QueryOptions<List<String>>(
    queryKey: todosKey,
    queryFn: (context) => fetchTodos(),
    staleTime: const StaleTime.duration(Duration(seconds: 30)),
  ));
  print(todos);

  // Observe: every change to the entry, as a sealed result.
  final observer = QueryObserver(
    client,
    QueryObserverOptions<List<String>>(
      queryKey: todosKey,
      queryFn: (context) => fetchTodos(),
    ),
  );
  final unsubscribe = observer.subscribe((result) {
    switch (result) {
      case QueryPending():
        print('loading');
      case QuerySuccess(:final data):
        print('todos: $data');
      case QueryError(:final error):
        print('failed: $error');
    }
  });

  // Mark stale and refetch what is observed.
  await client.invalidateQueries(filters: QueryFilters(queryKey: todosKey));

  unsubscribe();
  client.unmount();
  client.clear();
}

Future<List<String>> fetchTodos() async => ['Buy milk', 'Walk the dog'];

Where to go next

The API is grouped into categories:

Guides, recipes and live examples are on the documentation site: https://dualmeta-gmbh.github.io/query_kit/

Classes

AppFocusManager Managers
Tracks whether the app is in the foreground, so a mounted QueryClient can refetch stale queries when the user comes back (the refetchOnWindowFocus option) and resume work paused in the background.
CombinedData<T> Combining results
Every source has data; data is what the combiner made of it.
CombinedError<T> Combining results
A source failed and has no data to fall back on. retry() refetches the failed sources.
CombinedPending<T> Combining results
At least one source has nothing to show yet, and none has failed outright.
CombinedResult<T> Combining results
What several QueryResults amount to together: nothing to show yet (CombinedPending), a source that failed with nothing to show (CombinedError), or every source's data run through the combiner (CombinedData).
CombineMemo<T> Combining results
Remembers the last combination, so a combiner runs only when a source's data really changed and an equal result keeps its instance.
DefaultedMutationOptions<TData, TVariables, TOnMutateResult> Advanced
Mutation options with every default resolved. Only QueryClient produces one, and final keeps it that way; read it from Mutation.options or MutationObserver.options to see what a mutation actually runs with.
DefaultedQueryObserverOptions<TQueryData, TData> Advanced
QueryObserverOptionsBase with every default resolved: DefaultedQueryOptions plus the observer-only options, what a QueryObserver actually runs on.
DefaultedQueryOptions<TQueryData> Advanced
QueryOptions with every default resolved: what a Query actually runs on, read back as Query.options.
DefaultOptions Client
Client-wide defaults, passed to the QueryClient constructor or to QueryClient.setDefaultOptions.
Enabled Option values
Whether a query may fetch on its own — the enabled option.
EnabledNo Option values
The Enabled.no variant: the query never fetches on its own, but serves cached data and honours an explicit refetch.
EnabledWhen Option values
The Enabled.when variant: enabled while predicate returns true for the query.
EnabledYes Option values
The Enabled.yes variant: the query fetches on its own.
FetchBehavior<TQueryData> Advanced
Rewrites how a fetch runs.
FetchContext<TQueryData> Advanced
The mutable description of one fetch, handed to a FetchBehavior, which may replace fetchFn to change what the fetch does.
FetchMore Advanced
Which end of an infinite query a fetch is extending. Travels in FetchOptions.meta, and so ends up in QueryState.fetchMeta.
FetchOptions Advanced
Overrides for one call of Query.fetch, leaving the query's options untouched.
GcTime Option values
How long a query nobody observes stays in the cache — the gcTime option (the name is TanStack Query's: "garbage-collection time").
GcTimeDuration Option values
The GcTime.duration variant: collected duration after the query lost its last observer.
GcTimeNever Option values
The GcTime.never variant: an unobserved query stays cached until it is removed by hand or the client is cleared.
InfiniteData<TPageData, TPageParam> Infinite queries
The data an infinite query holds: every page fetched so far, and the param each was fetched with.
InfinitePageContext<TPageParam> Infinite queries
What a page function (InfiniteQueryOptions.pageFn) is handed: the param of the page to fetch, the direction, and the query's key, client, meta and cancellation token.
InfiniteQueryObserver<TPageData, TPageParam, TData> Observers
Watches one infinite query, and pages it.
InfiniteQueryObserverOptions<TPageData, TPageParam> Infinite queries
Observer options for a plain infinite query: no select, so the observer reports the InfiniteData the query holds, and two type arguments — the page and its param — name everything.
InfiniteQueryObserverOptionsBase<TPageData, TPageParam, TData> Infinite queries
InfiniteQueryOptions plus the observer-only options: select, placeholderData, the refetchOn* triggers, polling and retryOnMount.
InfiniteQueryOptions<TPageData, TPageParam> Infinite queries
Everything that describes an infinite query at the cache layer: a list whose pages are fetched one at a time, "load more" style.
InfiniteQuerySelectOptions<TPageData, TPageParam, TData> Infinite queries
Observer options for an infinite query whose observers see a projection of the pages: select is required and anchors TData.
InitialData<TQueryData> Option values
The value of QueryOptions.initialData: seed data written into the cache, as if it had been fetched.
InitialDataCompute<TQueryData> Option values
The InitialData.compute variant: a seed computed lazily, for as long as the query has no data.
InitialDataValue<TQueryData> Option values
The InitialData.value variant: a seed that is always present, even when data is null for a nullable data type.
MutateCallbacks<TData, TVariables, TOnMutateResult> Mutations
Callbacks a caller can attach to a single mutate call, on top of the ones in the options — for what only that call site cares about, such as closing a dialog or showing a snack bar.
Mutation<TData, TVariables, TOnMutateResult> Mutations
One mutation: its options, its state, and one run of its mutation function.
MutationAction Advanced
A state transition. Sealed, so the reducer is exhaustive.
MutationAdded Advanced
A mutation was created and appended to the cache, which happens the moment mutate is called (or a restored mutation is built into the cache). TanStack Query calls this the added event.
MutationCache Caches
Every mutation the client has run, in submission order.
MutationCacheEvent Advanced
Something happened to a mutation in the cache. The mutation-side twin of QueryCacheEvent, delivered to MutationCache.subscribe listeners.
MutationContinueAction Advanced
A paused run resumed — or a restored one was re-run. isPaused becomes false.
MutationDefaults Client
Mutation options that apply to many mutations at once: client-wide through DefaultOptions.mutations, or per mutation-key prefix through QueryClient.setMutationDefaults.
MutationError<TData, TVariables> Mutations
The run failed for good: retries, if any, are spent, and the error callbacks have run. error holds why; a cancelled run fails with a CancelledError.
MutationErrorAction Advanced
The run failed for good and every error callback has run. Status becomes error, the data is cleared, and the failure count is bumped one last time.
MutationFailedAction Advanced
One attempt failed and will be retried. Records the count and the reason; status stays pending.
MutationFilters Filters
Selects a set of mutations from the mutation cache.
MutationFunctionContext<TOnMutateResult> Mutations
What a MutationFnWithContext is told about the run it is part of.
MutationIdle<TData, TVariables> Mutations
Nothing has been submitted yet, or the observer was reset since: no variables, no data, no error. Call mutate to start a run.
MutationObserver<TData, TVariables, TOnMutateResult> Observers
Runs mutations and reports the latest one's state as a MutationResult.
MutationObserverAdded Advanced
An observer subscribed to the mutation, which also cancels its pending collection. TanStack Query calls this the observerAdded event.
MutationObserverOptionsUpdated Advanced
An observer's options were replaced while it stayed attached to the same mutation — a rebuild that changed a callback or retry, say. TanStack Query calls this the observerOptionsUpdated event.
MutationObserverRef Advanced
What a Mutation needs from an observer.
MutationObserverRemoved Advanced
An observer unsubscribed from the mutation; when it was the last one, the collection timer has been armed by the time this fires. TanStack Query calls this the observerRemoved event.
MutationOptions<TData, TVariables, TOnMutateResult> Mutations
Everything that describes a mutation: the write it performs, its callbacks, and how it retries, pauses and queues.
MutationPauseAction Advanced
The retryer suspended the run: offline, backgrounded, or blocked by its scope. isPaused becomes true.
MutationPending<TData, TVariables> Mutations
A run has been submitted and has not settled yet: onMutate, the mutation function or the settling callbacks are running, or the run is paused (isPaused) waiting for the network, the foreground or its MutationScope. variables holds what it was called with — what an optimistic UI shows meanwhile.
MutationPendingAction Advanced
A run started. Replaces the whole state: status pending, the run's variables, a fresh submittedAt, and isPaused when the run cannot start yet. Dispatched a second time once onMutate has run, when it produced a result or the run's pause changed meanwhile.
MutationRemoved Advanced
A mutation left the cache: garbage-collected after its last observer left, or removed through MutationCache.remove or MutationCache.clear. TanStack Query calls this the removed event.
MutationResult<TData, TVariables> Mutations
The result of observing one mutation: what a MutationObserver reports and what the Flutter binding's mutation helpers hand a widget.
MutationScope Mutations
Mutations sharing a scope run one at a time, in the order they started.
MutationState<TData, TVariables, TOnMutateResult> Mutations
A mutation's state at one point in time: its status, the variables of the current or last run, its data or error, and retry bookkeeping.
MutationStateObserver<TSelected> Observers
Watches a selection over every mutation in the cache, in submission order — not just the ones one observer started.
MutationSuccess<TData, TVariables> Mutations
The mutation function returned, and the success callbacks have run; data holds what it returned.
MutationSuccessAction Advanced
The mutation function resolved and every success callback has run. Status becomes success and the error and failure count are cleared.
MutationUpdated Advanced
A mutation's state changed. Emitted for every dispatched MutationAction — pending, success, error, pause, continue and the rest. TanStack Query calls this the updated event.
NotifyManager Managers
Batches cache notifications so one cascade of cache writes produces one round of listener calls.
OnlineManager Managers
Tracks whether the device believes it has a network connection.
PlaceholderData<TQueryData> Option values
The value of QueryObserverOptionsBase.placeholderData: data an observer shows while its query has none of its own.
PlaceholderDataCompute<TQueryData> Option values
The PlaceholderData.compute variant: a placeholder computed from what the observer showed last (TanStack Query: placeholderData: (previousData, previousQuery) => value).
PlaceholderDataKeepPrevious<TQueryData> Option values
The PlaceholderData.keepPrevious variant: while the observer's new key has no data, it keeps showing what it showed for the key before, flagged as isPlaceholderData. Equal to every other keepPrevious() of its type, so options that use it compare equal across rebuilds.
PlaceholderDataValue<TQueryData> Option values
The PlaceholderData.value variant: a fixed placeholder, shown whenever the query has no data of its own.
QueriesObserver<TQueryData, TData> Observers
Watches a list of queries at once and reports their results as one list, in the order the queries were given.
Query<TQueryData> Queries
One cache entry: a key, its options, its state, and the fetch machinery.
QueryAction Advanced
One change to a query's state — what a QueryUpdated cache event says happened.
QueryAdded Advanced
A query was created and put into the cache, by QueryCache.build or QueryCache.add — the first time anything used its key. TanStack Query calls this event added.
QueryCache Caches
Every query of one QueryClient, stored under its QueryKey.
QueryCacheEvent Advanced
Something happened to a query in the cache: what QueryCache.subscribe delivers to its listeners.
QueryCancelToken Queries
Handed to a query function, as QueryFunctionContext.signal, so it can abort work that is no longer wanted.
QueryClient Client
The entry point of query_kit: owns the caches and everything imperative — fetching, reading and writing cached data, invalidating, cancelling.
QueryContinueAction Advanced
A paused fetch resumed; fetchStatus is fetching again. TanStack Query calls this action continue.
QueryDefaults Client
Query options that apply to many queries at once: client-wide through DefaultOptions.queries, or per key prefix through QueryClient.setQueryDefaults.
QueryError<TData> Results
The last fetch failed after its retries, with error.
QueryErrorAction Advanced
A fetch failed for good: retries exhausted, or cancelled with neither silent nor revert — a reverting cancel restores the earlier state through QuerySetStateAction instead. Moves status to error, ends the fetch and flags existing data as invalidated. TanStack Query calls this action error.
QueryFailedAction Advanced
One attempt failed and will be retried. Records the count and the reason without touching status or the data. TanStack Query calls this action failed.
QueryFetchAction Advanced
A fetch started. Resets the failure count, records meta, and moves fetchStatus to fetching — or paused, when the network mode forbids starting. TanStack Query calls this action fetch.
QueryFilters Filters
Selects a set of queries from the cache.
QueryFunctionContext Queries
What a query function is handed: the client, the queryKey being fetched, the query's meta, and a cancel token, signal.
QueryInvalidateAction Advanced
The query was marked stale by QueryClient.invalidateQueries. Only isInvalidated changes; whether a refetch follows is the caller's decision. TanStack Query calls this action invalidate.
QueryKey Queries
An immutable, structurally compared cache key: what identifies a query in the cache.
QueryObserver<TQueryData, TData> Observers
Watches one query in a QueryClient's cache and reports its state to listeners as a QueryResult.
QueryObserverAdded Advanced
An observer subscribed to the query. Emitted the moment the observer attaches, which is also what cancels the query's pending garbage collection. TanStack Query calls this event observerAdded.
QueryObserverOptions<TData> Options
Observer options for a plain query: no select, so the observer reports the query's data as its own, and one type argument names both.
QueryObserverOptionsBase<TQueryData, TData> Options
QueryOptions plus everything only an observer cares about: when to refetch (refetchOnMount, refetchOnWindowFocus, refetchOnReconnect, refetchInterval, refetchIntervalInBackground, retryOnMount), what to show while there is no data (placeholderData), and what part of the data to report (select).
QueryObserverOptionsUpdated Advanced
An observer's options were replaced — a rebuild that changed staleTime, enabled or a callback, say. Emitted for every change of options, a key change included: moving an observer to a different key emits QueryObserverRemoved on the old query and QueryObserverAdded on the new one, and then this event on the new query. TanStack Query calls this event observerOptionsUpdated and orders it the same way.
QueryObserverRef Advanced
What a Query needs from an observer, without knowing what an observer is.
QueryObserverRemoved Advanced
An observer unsubscribed from the query. Emitted after the observer has been detached — and, when it was the last one, after the fetch in flight has been told to stop retrying and the garbage-collection timer has been started. TanStack Query calls this event observerRemoved.
QueryObserverResultsUpdated Advanced
An observer of the query delivered a new result to its listeners. Emitted once per delivery, after the listeners have run, so a devtools panel can mirror what the UI just saw. TanStack Query calls this event observerResultsUpdated.
QueryOptions<TQueryData> Options
Everything the cache entry for a query needs: its queryKey, the queryFn that fetches it, and how long and how hard to keep it — staleTime, gcTime, retry, retryDelay, networkMode, enabled, initialData, structuralSharing and meta.
QueryPauseAction Advanced
The fetch was suspended: the device is offline, or a retry is waiting for the app to return to the foreground. fetchStatus becomes paused. TanStack Query calls this action pause.
QueryPending<TData> Results
The query has nothing to show: no data and no error.
QueryRemoved Advanced
A query left the cache: it was garbage-collected after its gcTime without observers, or removed through QueryClient.removeQueries, QueryCache.remove or QueryCache.clear. TanStack Query calls this event removed.
QueryResult<TData> Results
The result of observing one query: what it holds, and what it is doing.
QuerySelectOptions<TQueryData, TData> Options
Observer options for a query whose observers see a projection of the cached data: what the cache holds (TQueryData) and what select makes of it (TData) — two type arguments, both anchored, TData by the required select.
QuerySetStateAction<TQueryData> Advanced
The whole state was replaced through Query.setState — a reset, a revert after cancellation, or a persistence layer restoring. TanStack Query calls this action setState.
QueryState<TQueryData> Queries
Everything a query holds at one point in time: its data or error, its status and fetchStatus, and the counters and timestamps behind them.
QuerySuccess<TData> Results
The query holds data — fetched, seeded, written by hand, or a placeholder — in data.
QuerySuccessAction<TQueryData> Advanced
Data arrived: from a fetch, or from a manual write through QueryClient.setQueryData. Bumps dataUpdateCount, clears the error and the invalidation, and — unless manual — ends the fetch. TanStack Query calls this action success.
QueryUpdated Advanced
A query's state changed. Emitted for every QueryAction — fetch, success, error, invalidate, pause, and the rest — so this is the event a devtools panel or a persister keys its work off. TanStack Query calls this event updated.
RefetchInterval Option values
Polling — the refetchInterval option.
RefetchIntervalDynamic Option values
The RefetchInterval.dynamic variant: the interval is computed from the query each time the timer is re-armed, and null stops polling.
RefetchIntervalEvery Option values
The RefetchInterval.every variant: polls at a fixed interval.
RefetchIntervalOff Option values
The RefetchInterval.off variant: no polling.
RefetchOn Option values
Whether an event refetches an observed query — the value of the refetchOnMount, refetchOnWindowFocus and refetchOnReconnect options.
RefetchOnAlways Option values
The RefetchOn.always variant: the event refetches, fresh data or not.
RefetchOnIfStale Option values
The RefetchOn.ifStale variant: the event refetches stale data only.
RefetchOnNever Option values
The RefetchOn.never variant: the event never refetches.
RefetchOnWhen Option values
The RefetchOn.when variant: the answer is computed per query each time the event fires.
RetryAlways Option values
The RetryPolicy.always variant: retries until an attempt succeeds.
RetryDelay Option values
How long to wait before the next attempt after a failure — the retryDelay option. Only consulted when RetryPolicy decided to retry.
RetryDelayDynamic Option values
The RetryDelay.dynamic variant: every wait computed by a function of the failure count and the error.
RetryDelayExponential Option values
The RetryDelay.exponential variant: min(base * 2^failureCount, maximum).
RetryDelayFixed Option values
The RetryDelay.fixed variant: the same wait before every retry.
RetryNever Option values
The RetryPolicy.never variant: the first failure is final.
RetryPolicy Option values
Whether a failed attempt is tried again — the retry option.
RetryTimes Option values
The RetryPolicy.times variant: up to count retries, so at most count + 1 attempts.
RetryWhen Option values
The RetryPolicy.when variant: retries while predicate returns true.
StaleTime Option values
How long fetched data counts as fresh — the staleTime option.
StaleTimeDuration Option values
The StaleTime.duration variant: fresh for duration after the fetch that produced the data, stale from then on.
StaleTimeDynamic Option values
The StaleTime.dynamic variant: a stale time computed from the query each time staleness is checked.
StaleTimeInfinite Option values
The StaleTime.infinite variant: never stale by time, so nothing refetches it on its own, but an invalidation or an explicit refetch still does — which is what separates it from StaleTimeStatic.
StaleTimeStatic Option values
The StaleTime.static variant: never stale, and — while an observer with this option holds the query — never refetched by a trigger either: not on mount, focus, reconnect, invalidation or refetchQueries.
StructurallyShareable<T>
A value class that structural sharing may walk into.

Enums

FetchDirection Queries
Which end of an infinite query is being fetched.
FetchStatus Queries
What a query is doing right now: fetching, paused, or nothing.
MutationStatus Mutations
Where a mutation is in its life: idle before the first run, pending while running (or paused), then success or error until the next run or a reset.
NetworkMode Option values
How connectivity gates fetching — the networkMode option, for queries and mutations alike. Connectivity comes from the client's OnlineManager.
QueryStatus Queries
What a query holds: nothing yet, data, or an error.
QueryTypeFilter Filters
Which queries a filtered operation applies to, by whether anything is observing them: the value of QueryFilters.type.
RefetchType Filters
Which queries invalidateQueries refetches once it has marked them stale. RefetchType.none marks without refetching anything.

Extensions

CombineQueryResultList on List<QueryResult<T>> Combining results
combine over a list of results of one type — a QueriesObserver's results, say, one per item of a dynamic list — by the same rules as a record of them, and combineWith for that list plus one more source of another type.
CombineQueryResults2 on (QueryResult<A>, QueryResult<B>) Combining results
combine over a record of two results: runs the combiner once both have data, by the rules on CombinedResult.
CombineQueryResults3 on (QueryResult<A>, QueryResult<B>, QueryResult<C>) Combining results
combine over a record of three results: runs the combiner once all three have data, by the rules on CombinedResult.
CombineQueryResults4 on (QueryResult<A>, QueryResult<B>, QueryResult<C>, QueryResult<D>) Combining results
combine over a record of four results: runs the combiner once all four have data, by the rules on CombinedResult.
CombineQueryResults5 on (QueryResult<A>, QueryResult<B>, QueryResult<C>, QueryResult<D>, QueryResult<E>) Combining results
combine over a record of five results: runs the combiner once all five have data, by the rules on CombinedResult.
CombineQueryResults6 on (QueryResult<A>, QueryResult<B>, QueryResult<C>, QueryResult<D>, QueryResult<E>, QueryResult<F>) Combining results
combine over a record of six results: runs the combiner once all six have data, by the rules on CombinedResult. Past six, combine a list of what the sources have in common — <QueryResult<Object?>>[...] at worst — and cast in the combiner; a CombinedResult is not a source, so two combinations cannot be combined.
OptionalQueryResult on QueryResult<T> Combining results
Marks a source a combination can do without — see optional.

Functions

noStructuralSharing<TQueryData>() → StructuralSharing<TQueryData>
The opt-out for QueryOptions.structuralSharing: every write keeps the incoming value, so every refetch reports a new instance, and so does every select. TanStack Query spells this structuralSharing: false.
replaceEqualDeep<T>(Object? previous, T next, [int depth = 0]) → T
Returns previous when next is deep-equal to it, and otherwise next with every deep-equal part swapped for the instance previous already held. This is the default structural sharing of every query, and the reason a refetch that brings back the same data does not rebuild anything: unchanged data keeps its instance, so identical checks and == short-circuits downstream stay cheap and true.

Typedefs

BatchNotifyFunction = void Function(void callback()) Managers
Wraps the delivery of a whole batch: must call the callback it is given exactly once. Install one with NotifyManager.setBatchNotifyFunction — in a UI framework, to apply every update of a batch in one frame. The default calls it directly.
FocusSetup = void Function() Function(void setFocused(bool? focused)) Managers
An adapter for AppFocusManager.setEventListener: installs a platform listener that reports focus through setFocused, and returns a function that removes the listener again.
InfinitePageFn<TPageData, TPageParam> = FutureOr<TPageData> Function(InfinitePageContext<TPageParam> context) Infinite queries
Fetches one page, given the context that names its param — the page function of an infinite query (InfiniteQueryOptions.pageFn).
MutationFn<TData, TVariables> = FutureOr<TData> Function(TVariables variables) Mutations
The function a mutation runs: it performs the write for variables and returns (or completes with) the server's answer, which becomes the mutation's data. Throwing, or completing with an error, fails the attempt. Set through MutationOptions.mutationFn.
MutationFnWithContext<TData, TVariables, TOnMutateResult> = FutureOr<TData> Function(TVariables variables, MutationFunctionContext<TOnMutateResult> context) Mutations
A MutationFn that also receives the MutationFunctionContext of its run. Set through MutationOptions.mutationFnWithContext.
MutationObserverListener<TData, TVariables> = void Function(MutationResult<TData, TVariables> result) Observers
What a MutationObserver.subscribe listener receives: the new MutationResult, each time it changes.
MutationStateSelect<TSelected> = TSelected Function(Mutation<Object?, Object?, Object?> mutation) Observers
Selects a value from each matching mutation, including concurrent runs sharing one key. The mutation's type arguments are erased because filters span data types; TypedMutationStateSelect is the typed form.
NotifyFunction = void Function(void callback()) Managers
Wraps the delivery of a single notification: must call the callback it is given exactly once. Install one with NotifyManager.setNotifyFunction, for example to run each listener inside a zone or an error boundary. The default calls it directly.
OnlineSetup = void Function() Function(void setOnline(bool online)) Managers
An adapter for OnlineManager.setEventListener: installs a platform listener that reports connectivity through setOnline, and returns a function that removes the listener again.
OnMutate<TVariables, TOnMutateResult> = FutureOr<TOnMutateResult?> Function(TVariables variables) Mutations
The signature of MutationOptions.onMutate: runs before the mutation function with its variables, and what it returns is the onMutateResult the other callbacks receive — typically a snapshot to roll an optimistic update back to. A returned future is awaited.
OnMutationError<TVariables, TOnMutateResult> = FutureOr<void> Function(Object error, StackTrace stackTrace, TVariables variables, TOnMutateResult? onMutateResult) Mutations
The signature of MutationOptions.onError and MutateCallbacks.onError: the error and where it was thrown, the variables, and what onMutate returned (null when onMutate itself threw or there is none).
OnMutationSettled<TData, TVariables, TOnMutateResult> = FutureOr<void> Function(TData? data, Object? error, StackTrace? stackTrace, TVariables variables, TOnMutateResult? onMutateResult) Mutations
The signature of MutationOptions.onSettled and MutateCallbacks.onSettled: whichever of data and error applies (the other is null), the error's stack trace, the variables, and what onMutate returned.
OnMutationSuccess<TData, TVariables, TOnMutateResult> = FutureOr<void> Function(TData data, TVariables variables, TOnMutateResult? onMutateResult) Mutations
The signature of MutationOptions.onSuccess and MutateCallbacks.onSuccess: the data, the variables, and what onMutate returned.
PageParamFn<TPageData, TPageParam> = TPageParam? Function(TPageData page, List<TPageData> pages, TPageParam pageParam, List<TPageParam> pageParams) Infinite queries
Where the next (or previous) page starts, or null when there is none.
QueryFn<TQueryData> = FutureOr<TQueryData> Function(QueryFunctionContext context) Queries
The function a query runs to get its data: handed a QueryFunctionContext, it returns the data or a future of it. A throw fails the attempt, which QueryOptions.retry may then retry.
QueryObserverListener<TData> = void Function(QueryResult<TData> result) Observers
What a QueryObserver.subscribe listener receives: the new QueryResult, each time it changes.
QueryRefetch<TData> = Future<QueryResult<TData>> Function({bool cancelRefetch}) Results
Refetches the query behind a result.
ScheduleFunction = void Function(void callback()) Managers
Schedules when a batch of notifications runs: given the delivery as a callback, runs it now or later. The default is scheduleMicrotask; install one with NotifyManager.setScheduler (the Flutter binding installs a build-phase-aware one).
SelectFn<TQueryData, TData> = TData Function(TQueryData data) Queries
Projects a query's data into what an observer reports — the select of a QuerySelectOptions. It runs on the observer's side, so every observer of one query may select something different from the same cached data.
StructuralSharing<TQueryData> = TQueryData Function(TQueryData? previous, TQueryData next)
Decides what is written into the cache when new data arrives, given what was there before.
TypedMutationStateSelect<TData, TVariables, TOnMutateResult, TSelected> = TSelected Function(Mutation<TData, TVariables, TOnMutateResult> mutation) Observers
MutationStateSelect over mutations of one type: what MutationStateObserver.typed takes.

Exceptions / Errors

CancelledError Errors
What a cancelled fetch fails with.
MissingMutationFunctionError Errors
Thrown when a mutation runs without a function: neither MutationOptions.mutationFn nor mutationFnWithContext was set, and no default was registered for its key with QueryClient.setMutationDefaults. The mutation fails with it at once, without retrying.
MissingQueryFunctionError Errors
Thrown when a query is fetched with no query function anywhere in its options chain.
QueryDataTypeError Errors
Thrown when a query is read as one data type but holds another — or when an erased default (QueryDefaults.queryFn, structuralSharing, MutationDefaults.mutationFn) hands back a value of the wrong type.