Define, run, and track a write

Write a mutation as a provider method. Track it with MutationToken and run it with ref.invoke(call).

The parts of a mutation

mutate(token, body, concurrency: ...) creates a Call<R, State> that you can pass to ref.invoke.

Track the mutation

late final renameMut = mutation<void>(#rename)

Run the update

await ref.invoke(provider.rename(...))

Read its state

Watch the token with ref.watch(token) to see Idle, Pending, Success, or Error.

How a mutation becomes a call

miniriverpod puts the work for each mutation in a separate Call. Pass it to invoke when you're ready to run the update.

Run a mutation with ref.invoke

Run the mutation with ref.invoke so the caller can handle cancellation and disposal.

Run the call

await ref.invoke(userProvider.rename('Alice'));

What to do when calls overlap

concurrent    Run all calls in parallel by default.
queue         Run calls in arrival order and keep going after an error.
restart       Cancel the previous run and keep the latest call.
dropLatest    Skip a new call while one is already running.

Show a change immediately and keep the latest call

Update AsyncData immediately to reflect the user's action, then bring it into line with the server's response.

class UserProvider extends AsyncProvider<User?> {
  UserProvider() : super.args(null);

  @override
  Future<User?> build(Ref<AsyncValue<User?>> ref) async {
    return ref.watch(apiProvider).me();
  }

  late final renameMut = mutation<void>(#rename);

  Call<void, AsyncValue<User?>> rename(String newName) => mutate(
    renameMut,
    (ref) async {
      final cur = ref.watch(this).valueOrNull;
      ref.state = AsyncData((cur ?? const User()).copyWith(name: newName), isRefreshing: true);

      final api = ref.watch(apiProvider);
      await api.rename(newName);
      ref.state = AsyncData(await api.me());
    },
    concurrency: Concurrency.restart,
  );
}

final userProvider = UserProvider();
With restart, an earlier caller can receive CancelledMutation.
With dropLatest, a call that arrives while work is underway can receive DroppedMutation.
Catch expected cancellations in the UI so they don't show up as errors to the user.

Where to go next

Use providers in Flutter

Show mutation state in a ConsumerWidget or ConsumerStatefulWidget.

See the Flutter API

API Reference

Look up invoke, mutation, mutate, and MutationState.

Look up an API