QueryContext extension Reading queries Mutations Infinite queries

Reads queries and mutations straight from a BuildContext, in build.

One of the four equal ways to read a query; the others are QueryMixin, the builder widgets such as QueryBuilder, and the controllers such as QueryController. This one is the flattest: it works in a StatelessWidget, needs no wrapper widget, and its rebuilds are per-reader — when a query changes, only the widgets that read that query rebuild.

class TaskScreen extends StatelessWidget {
  const TaskScreen(this.id, {super.key});

  final String id;

  @override
  Widget build(BuildContext context) {
    final task = context.query(taskQuery(id));
    final rename = context.mutation(renameTask(id));
    return switch (task) {
      QueryPending() => const CircularProgressIndicator(),
      QueryError(:final error) => Text('$error'),
      QuerySuccess(:final data) => ListTile(
          title: Text(data.name),
          trailing: IconButton(
            icon: const Icon(Icons.edit),
            onPressed: rename.value.isPending
                ? null
                : () => rename.mutate('Renamed'),
          ),
        ),
    };
  }
}

Four members: query for plain options, selectQuery for options with a select, infiniteQuery, which returns an InfiniteQueryController because paging lives there, and mutation, which returns a MutationController.

Identity

Every reading widget gets observers of its own; what is shared is the query in the cache, so two widgets reading one key still cost one request, and they never fight over one observer's select, enabled or polling interval. Within one widget a read is identified by its key and its types, so a read inside an if is fine — there is no rule about call order. Pass id: to tell apart two reads of one key with different selectors of the same output type; reading two of them without one is caught in debug builds.

An id then takes the key's place in the read's identity (the types stay part of it): a read that carries one keeps its observer when its key changes. That is what PlaceholderData.compute((previous, _) => previous) needs to keep showing the previous key's data while the next key loads; without an id, a new key is a new observer with nothing previous to show.

A mutation is identified by its id, else by its mutationKey, each together with its three types; see mutation.

When a read is released

A key the widget read in its last build but not in this one is released after the frame, and so is a mutation. Everything goes when the widget unmounts.

A widget that stops calling context.query altogether gives no signal Flutter can see, so its last observers stay until it unmounts. Put a conditional read in a small widget of its own, and the condition becomes that widget's presence in the tree.

Read in build, through the widget's own context

A read belongs to the element whose context it went through, rebuilds that element, and lives as long as that element's own builds keep reading it.

  • Only in build. The read is reconciled against what the widget read in its last build. A context.query in a tap handler creates an observer that is only matched up at the next build. Read in build and act on the result from the handler.

  • Nested builders make additive reads. A read through the outer context inside a ValueListenableBuilder, AnimatedBuilder or LayoutBuilder callback runs later than build, and it releases nothing the widget's own build read. A key such a callback stops reading stays subscribed until the widget's next own build that reads through this context, or its unmount. A build that reads nothing releases nothing, and neither does a new widget instance from the parent on its own: the first read through this context after it — a nested builder's included — counts as that own build. And an own build that reads keeps only what it reads: a nested builder it does not re-run — its widget kept in a field — reads nothing then, so its keys are released after that frame while it still shows them, until it runs again and reads. (Flutter does not re-run such a builder when this widget rebuilds, so it shows a change only when it runs again anyway.) Read in build, or give the nested part a widget of its own.

  • Cache writes during a nested build. A nested builder that writes the cache while it builds, then rereads through the outer context, moves the baseline the owner compares against before the owner's own notification arrives. If that reread has no buildWhen, the binding remembers the change and the owner rebuilds as well, whatever predicate the owner itself reads with. If the reread has a buildWhen — even one that always returns true — the owner can go on showing the old data (and, for an infinite query, the old paging flags). Read through the nested builder's own context, or give it a widget of its own. And write the cache from a callback, not from build: a write on every build, even of identical data, rebuilds the owner on every frame.

  • A LayoutBuilder's own context. Reads through the context a LayoutBuilder, SliverLayoutBuilder or OrientationBuilder hands its builder start over whenever that builder provably runs: its constraints changed (the wide layout's key goes after a resize), its parent rebuilt it, or one of its own reads notified. A nested builder handed that context is additive, as above. A rebuild caused by an InheritedWidget the builder depends on carries no signal, so a key picked from an inherited value stays subscribed until the next resize, notification or parent rebuild. A key that depends on anything the builder reads belongs in a widget of its own below the LayoutBuilder — LayoutBuilder(builder: (_, c) => c.maxWidth > 600 ? const WideTasks() : const NarrowTasks()), each reading in its own build — and goes with that widget.

  • Dialogs, sheets and overlays read through their own context. Reading through a page's context from a showDialog or bottom-sheet builder rebuilds the page, not the dialog, and the page's next own build that reads through its context releases the read while the dialog may still show it. Read through the builder's own context, or in a widget inside the dialog.

  • Never through a list's item-builder context. The context a ListView.builder, GridView.builder, PageView.builder or another lazily built list hands its itemBuilder belongs to the whole list, not the row: rows are built piecemeal as they scroll in, and a read cannot tell which row it belongs to. In debug builds such a read throws a FlutterError naming the fix. In release builds the reads are additive: no row on screen loses its subscription, and rows scrolled away stay subscribed until the list is rebuilt or unmounts. Give each row a widget of its own:

    ListView.builder(
      itemCount: ids.length,
      itemBuilder: (_, i) => TaskTile(ids[i]), // reads in TaskTile.build
    )
    

The client is always the provider's

There is no client: parameter, on purpose: a BuildContext names exactly one QueryClientProvider, and a second way to say which client would only leave a reader wondering which one won. For a client that is not the provider's, use a builder widget's client:, a controller, or override QueryMixin.queryClient. Without a provider above, every member throws a FlutterError that says so.

on

Methods

infiniteQuery<TPageData, TPageParam, TData>(InfiniteQueryObserverOptionsBase<TPageData, TPageParam, TData> options, {Object? id, BuildWhen<QueryResult<TData>>? buildWhen}) → InfiniteQueryController<TPageData, TPageParam, TData>

Available on BuildContext, provided by the QueryContext extension

query for an infinite query. Returns the controller rather than the result, because paging lives on it: the pages are in its value, and InfiniteQueryController.fetchNextPage and its siblings load more.
mutation<TData, TVariables, TOnMutateResult>(MutationOptions<TData, TVariables, TOnMutateResult> options, {Object? id, BuildWhen<MutationResult<TData, TVariables>>? buildWhen}) → MutationController<TData, TVariables, TOnMutateResult>

Available on BuildContext, provided by the QueryContext extension

A mutation owned by this widget, as a MutationController.
query<TData>(QueryObserverOptions<TData> options, {Object? id, BuildWhen<QueryResult<TData>>? buildWhen}) → QueryResult<TData>

Available on BuildContext, provided by the QueryContext extension

Subscribes this widget to options's query and returns its current result.
selectQuery<TQueryData, TData>(QuerySelectOptions<TQueryData, TData> options, {Object? id, BuildWhen<QueryResult<TData>>? buildWhen}) → QueryResult<TData>

Available on BuildContext, provided by the QueryContext extension

query for a query with a select: the cache holds TQueryData, this widget sees TData.