Mutations
A mutation sends a change to the server, such as a new todo. Run it from a button, show its progress on any screen, tell the user when it fails, and update the cache before the server answers.
This one adds a todo:
final addTodo = Mutation( mutationKey: const ['todos', 'add'], mutationFn: (String title) => api.addTodo(title), onSuccess: (todo, title, context, client) { return client.invalidateQueries(queryKey: ['todos']); },);Type the parameter of mutationFn, like String title above, and Dart infers the other types from it. The exception is onMutate and onError: type their variables too, as in onMutate: (String title, client). Otherwise the variables can be Object?, and only the build reports it (The build fails with Object? in onMutate or onError). The mutationKey lets any widget find the mutation’s runs. A run is one mutate call (Mutation runs). Mutation options lists every option.
Running a mutation
Section titled “Running a mutation”Call mutate on the definition, and pass it context.queryClient. Any widget runs a mutation this way, a StatelessWidget included:
class AddTodoButton extends StatelessWidget { const AddTodoButton({super.key});
@override Widget build(BuildContext context) { return FilledButton( onPressed: () => addTodo.mutate('Buy milk', context.queryClient), child: const Text('Add'), ); }}mutatestarts a run and returns at once. When the run fails, the error goes to the run’s state and to the callbacks, not to the caller.- A definition holds no state. The run belongs to the client’s cache, not to a widget, so it goes on after the button leaves the screen.
context.queryClientis the client the widgets use: the nearestFueryProvider’s, orFuery.clientwithout one. Passing it puts the run in the cache that the MutationState widgets read.- Without a client, the run uses
Fuery.client. Code without aBuildContext, such as a cubit, runs a mutation this way.
Showing every run of a mutation
Section titled “Showing every run of a mutation”The MutationState widgets show the runs of a mutation on any screen. They find the runs by the definition’s mutationKey, wherever each run started: the definition’s mutate, a MutationBuilder, a useMutation, a cubit, or restore(mutations:). They work in a StatelessWidget.
| Widget | Builds from, or hears |
|---|---|
MutationStateBuilder |
The MutationState of every run, oldest first |
MutationStateSelector |
A value selected from those states. It rebuilds only when the value changes. |
MutationStateListener |
Each change of each run, for side effects |
The button above, turned off while a todo is being added:
MutationStateSelector( mutation: addTodo, selector: (runs) => runs.any((run) => run.isPending), builder: (context, adding) => FilledButton( onPressed: adding ? null : () => addTodo.mutate('Buy milk', context.queryClient), child: Text(adding ? 'Adding…' : 'Add'), ),)The titles on their way to the server, typed as String like the definition’s variables:
MutationStateBuilder( mutation: addTodo, builder: (context, runs) => Column( children: [ for (final run in runs) if (run case MutationState(isPending: true, :final variables?)) ListTile(title: Text(variables)), ], ),)Matching runs
Section titled “Matching runs”- Given a
Mutation, the widgets show the runs whosemutationKeyequals its own exactly, typed like the definition. - Runs of another definition with the same key and types count too.
- A run of other types under the key is left out and reported once to
onUncaughtError. Give each definition a key of its own. - A definition without a
mutationKeyfails an assert in debug builds. - Given
MutationFilters, the widgets show the runs of any mutation that match them, asclient.mutationCache.findAllfinds them: by key prefix,exactkey,status, orpredicate. Their states are typedObject?. - Without a
statusfilter, settled runs match too.
Run order and lifetime
Section titled “Run order and lifetime”- Runs are listed oldest first, so
runs.lastOrNullis the latest. - A run stays
gcTime(default: 5 minutes) after it settles, so build an indicator fromisPending, not from the number of runs. - A mounted
MutationBuilderkeeps its latest run for as long as it shows it. client.clear()removes every run.
Client and cost
Section titled “Client and cost”- Only the runs of the widget’s client count: the nearest
FueryProvider’s, orFuery.client. - The widgets only read. They never run a mutation and apply none of the definition’s options, so a definition built in
buildcosts nothing.
Telling the user a mutation failed
Section titled “Telling the user a mutation failed”A failed mutate puts the error in the run’s state instead of throwing it. A MutationStateListener hears every run of the mutation, from any screen, and gets each run’s new state:
MutationStateListener( mutation: addTodo, listenWhen: (previous, current) => current.isError, listener: (context, run) => ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Could not add "${run.variables}"')), ), child: const TodoScreen(),)- Fuery calls it once for each run that changed, so two failed runs give two calls.
listenWhencompares that run’s previous state with its new one.- It isn’t called for the states runs already had when it mounted, or for a run that the cache removes.
- It hears restored runs and runs from other screens too, so mount it once, where the message belongs.
A MutationListener hears only the runs of the observer it gets. Given a definition, it creates an observer of its own that nothing runs, so it hears nothing. In debug builds, it also prints a warning. See A MutationListener never runs.
Acting after one call succeeds
Section titled “Acting after one call succeeds”mutateAsync returns the data when the run succeeds, and throws the error when it fails. Await it for an effect of one call, such as closing the form that saved:
FilledButton( onPressed: () async { try { await addTodo.mutateAsync('Buy milk', context.queryClient); } catch (_) { return; // The MutationStateListener above reports the failure. } if (context.mounted) Navigator.pop(context); }, child: const Text('Add'),)- Check
context.mountedafter theawait. The user can leave the screen while the run is pending. - Catch the error. An error that nothing catches reaches the zone as an uncaught error.
Showing only the runs a widget starts
Section titled “Showing only the runs a widget starts”A MutationBuilder keeps an observer of its own, and shows only the runs it starts. Use it when a widget’s state must leave out the runs started elsewhere, such as a Save button on each of several forms:
MutationBuilder( mutation: addTodo, builder: (context, state) => FilledButton( onPressed: state.isPending ? null : () => state.mutate('Buy milk'), child: Text(state.isPending ? 'Adding…' : 'Add'), ),)state.mutate('Buy milk')starts a run through this widget.await state.mutateAsync('Buy milk')returns the data, and throws on error.stateshows the latest run that this widget started. A run started withaddTodo.mutate, or by another widget, doesn’t show in it.state.reset()returns the state to idle.- The widget uses the client of the nearest
FueryProvider, orFuery.clientwithout one. - In a
HookWidget,useMutation(addTodo)returns the same result. See Hooks.
Mutation results lists every member and field of state.
To react to one call of this widget, pass MutateOptions to state.mutate. Its callbacks run after the mutation’s own, once the call settles:
state.mutate( 'Buy milk', MutateOptions(onSuccess: (todo, title, _, __) => showAddedSnackBar(todo)),);- A later
mutatecall on the same observer replaces them. Only the latest call’s callbacks run. reset()drops them. Unmounting the widget drops them too.- A shared observer runs them whether or not a widget listens to it. Check
context.mountedbefore you use aBuildContextin them.
Callbacks
Section titled “Callbacks”onMutate runs before mutationFn. onSuccess, onError, and onSettled run after it. Callbacks lists their arguments and order.
- The last argument,
client, is the client running the mutation: the one passed to the definition’smutate, the one a widget got fromFueryProvider, or the one passed toobserve(client:). Use it instead ofFuery.client, so the callbacks reach the right cache in tests too. - When
onMutate,onSuccess,onError, oronSettledreturns a future, the run stays pending until the future completes. Fuery doesn’t awaitMutateOptionscallbacks.addTodoabove returns theinvalidateQueriesfuture fromonSuccess, so the button shows Adding… until the list has refetched.
Optimistic updates
Section titled “Optimistic updates”An optimistic update changes the cache before the server answers, so the screen responds at once:
- In
onMutate, cancel refetches of the query, so none overwrites the update. - Still in
onMutate, write the new data and return the old data. The other callbacks receive it ascontext. - In
onError, write the old data back. - In
onSettled, invalidate the query to refetch what the server has.
todosQuery and todosKey are the query and its key:
final deleteTodo = Mutation( mutationFn: (int id) => api.deleteTodo(id), onMutate: (int id, client) async { // Keep a refetch in flight from overwriting the optimistic update. await client.cancelQueries(queryKey: todosKey); final previous = client.getData(todosQuery); client.updateData( todosQuery, (todos) => todos?.where((todo) => todo.id != id).toList(), ); return previous; }, onError: (error, int id, previous, client) { if (previous != null) client.setData(todosQuery, previous); }, onSettled: (_, __, ___, ____, client) { return client.invalidateQueries(queryKey: todosKey); },);Try it in the playground: add todos, and fail a request to see the rollback.
Mutations without variables
Section titled “Mutations without variables”Use NoVariablesMutation for a mutation that takes nothing, such as logging out. Its mutationFn and callbacks leave out the variables (NoVariablesMutation):
final logoutMutation = NoVariablesMutation( mutationFn: () => api.logout(),);Run it with logoutMutation.mutate(), so a button takes the tear-off: onPressed: logoutMutation.mutate. logoutMutation.mutateAsync() returns the data.
- On a client other than
Fuery.client, passnullfor the variables first:logoutMutation.mutate(null, context.queryClient). - A
MutationBuilderoruseMutationresult hasvoidvariables, so it runs the mutation withstate.mutate(null). The callbacks of one call keep the variables argument, which isnull. - Its observer from
observe(), aNoVariablesMutationObserver, runs it withmutate().
After logging out, empty the cache once the app has left the screens that used it. Clearing everything at logout explains why the order matters.
Retries and ordering
Section titled “Retries and ordering”A mutation retries only when you set retry, because repeating a write is not always safe. RetryPolicy.count(2) allows two more attempts, 1 second and then 2 seconds apart. Mutations that share a scope run one at a time, in the order they started:
final saveDraft = Mutation( mutationFn: (Draft draft) => api.saveDraft(draft), retry: const RetryPolicy.count(2), scope: const MutationScope('drafts'),);A run that waits for its turn in the scope reports isPaused, and so does a run that waits for the network. To keep a waiting run across a restart, give the mutation a persist (Persisting mutations).
Sharing one observer
Section titled “Sharing one observer”The definition’s mutate and the MutationState widgets need no observer of your own. A cubit runs a mutation from its definition too (Mutations from a cubit or bloc). Share one observer only when several widgets must follow the runs of one screen and no others.
addTodo.observe() returns a MutationObserver, and every widget given it uses it as it is. Here the app bar shows a progress bar while this screen’s form saves. A MutationStateSelector would also show the runs that other screens start:
class _AddTodoScreenState extends State<AddTodoScreen> { late final adding = addTodo.observe(client: context.queryClient);
@override void dispose() { adding.reset(); super.dispose(); }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('New todo'), bottom: PreferredSize( preferredSize: const Size.fromHeight(4), child: MutationSelector( mutation: adding, selector: (state) => state.isPending, builder: (context, saving) => saving ? const LinearProgressIndicator() : const SizedBox(height: 4), ), ), ), body: AddTodoForm(onSubmit: adding.mutate), ); }}To close the screen after its own call succeeds, you don’t need a shared observer. Await mutateAsync (Acting after one call succeeds).
- Create the observer once, in a
Statefield or a cubit.observe()inbuildreturns a new, idle observer on every rebuild. observe()usesFuery.clientunless you passclient:. Under aFueryProviderwith its own client, passcontext.queryClient, as above.- Call
reset()indispose. It drops the callbacks of the latestmutatecall, which belong to this screen. A widget given the definition resets its own observer when it unmounts. - A
MutationListener,MutationSelector, orMutationBuildergiven the observer hears every run it starts, wherever it is called.
In the example app
Section titled “In the example app”- The feed mutations have an optimistic like with a rollback, and a comment that pauses while offline.
- The feed runs each like from its definition, and reports every failed like with a
MutationStateListener. - The post screen sends a comment from its definition, and lists the comments on their way with a
MutationStateBuilder. - The compose screen runs a new post from a
MutationBuilder, whose button shows only its own run.
The example’s README maps each screen to what it shows.