Skip to content

Mutations ​

While queries are meant for fetching data without modifying server state, mutations are designed for side-effects: creating, updating, or deleting data.

MutationObserver<TData, TError, TVariables, TContext> encapsulates:

  • Execution and pending state management.
  • Preventing duplicate concurrent submissions.
  • Optimistic updates via context rollbacks.
  • Lifecycle callbacks: onMutate, onSuccess, onError, and onSettled.

Defining a Mutation ​

dart
final mutation = MutationObserver<Todo, Exception, String, List<Todo>>(
  options: MutationOptions(
    mutationFn: (newTitle) => api.createTodo(newTitle),

    // 1. Called before mutation executes (ideal for optimistic updates)
    onMutate: (title) async {
      final previousTodos = cache.getQueryData<List<Todo>, Exception>(['todos']) ?? [];
      
      // Optimistically insert item
      cache.setQueryData<List<Todo>, Exception>(['todos'], (current) {
        return [...(current ?? []), Todo(id: -1, title: title)];
      });

      // Returned context is forwarded to onError and onSettled
      return previousTodos;
    },

    // 2. Called on success
    onSuccess: (data, variables, context) {
      print('Todo created with ID: ${data.id}');
    },

    // 3. Called if mutation fails
    onError: (error, variables, context) {
      // Revert cache back to previous snapshot
      if (context != null) {
        cache.setQueryData<List<Todo>, Exception>(['todos'], (_) => context);
      }
    },

    // 4. Called always upon completion
    onSettled: (data, error, variables, context) {
      // Invalidate to synchronize with server
      cache.invalidateQueries(['todos']);
    },
  ),
);

Triggering Mutations ​

There are two methods to trigger a mutation:

1. mutate (Callbacks-oriented) ​

dart
await mutation.mutate('Buy groceries');

Errors are trapped inside the mutation state machine and routed to onError without throwing.

2. mutateAsync (Futures-oriented) ​

dart
try {
  final newTodo = await mutation.mutateAsync('Buy groceries');
  print('Result: $newTodo');
} catch (e) {
  print('Mutation threw: $e');
}

Throws on failure so caller can handle errors using standard try/catch.


Resetting State ​

To return a mutation to its initial idle state, call reset():

dart
mutation.reset();
print(mutation.mutation.isIdle); // true

Released under the MIT License.