Luồng ghi luôn rõ ràng.

Định nghĩa mutation như các phương thức provider, theo dõi state bằng MutationToken, và thực thi qua ref.invoke(call).

Các khối xây dựng của mutation

Một mutation là một Call<R, State> được trả về từ mutate(token, body, concurrency: ...).

Token

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

Execution

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

State

Idle / Pending / Success / Error via ref.watch(token)

Lưu ý

Khác với API kiểu notifier.method(), miniriverpod biến việc thực thi mutation thành một đối tượng call hạng nhất.

Thực thi một mutation

Dùng ref.invoke để các hành vi hủy và bỏ qua được hiển thị cho caller.

Chạy

Tùy chọn đồng thời

concurrent : run all calls in parallel (default).
queue      : FIFO; keep running queued calls even after an error.
restart    : cancel previous run, keep only latest call.
dropLatest : drop incoming calls while one is running.

Ví dụ: cập nhật lạc quan + restart

Một mẫu ghi phổ biến cập nhật AsyncData theo kiểu lạc quan, rồi đồng bộ với phản hồi từ máy chủ.

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

  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,
  );
}
restart có thể ném CancelledMutation tới các caller cũ hơn.
dropLatest có thể ném DroppedMutation khi đang bận.
Hãy bắt chúng trong UI khi bạn muốn bỏ qua các lỗi hủy tạm thời.

Buoc tiep theo

Flutter API

Liên kết state của mutation với UI bằng ConsumerWidget hoặc ConsumerStatefulWidget.

Mở Flutter API

API Reference

Xem nhanh các kiểu invoke, mutation, mutate và MutationState.

Mở tài liệu API