Read paths: watch, read, and listen.

Provider gives synchronous state. AsyncProvider returns AsyncValue and can expose Future and Stream with strict lifecycle handling.

Provider Types

Choose provider type by data source and update frequency.

Provider<T>

Synchronous values and local derived state

AsyncProvider<T>

Future/Stream-driven state as AsyncValue<T>

provider.future

Selector that exposes Provider<Future<T>>

Tip

If state comes from network or stream, prefer AsyncProvider first. Keep Provider for pure synchronous logic.

Read API Matrix

Use watch in build paths, read for one-shot access, and listen for side effects.

Most common

final value = ref.watch(myProvider);

watch / read / listen

ref.watch(provider)  : subscribe and rebuild when value changes.
ref.read(provider)   : read current snapshot without subscribing.
container.listen(...) : callback-driven updates; optional fireImmediately.

Future and Stream with AsyncProvider

A single AsyncProvider can return a Future or bind a Stream via ref.emit(stream).

user_sources.dart
final currentUser = AsyncProvider<User>((ref) async {
  final api = ref.watch(apiProvider);
  return api.me();
});

final liveUser = AsyncProvider<User>((ref) {
  final stream = ref.watch(apiProvider).live();
  ref.emit(stream);
  return const User(name: 'Loading...');
}, autoDispose: true, autoDisposeDelay: const Duration(milliseconds: 250));

// Await as Future
final user = await ref.watch(currentUser.future);
ref.emit(stream) cancels prior subscription on rebuild, invalidate, and dispose.
AsyncValue is a sealed class: AsyncLoading / AsyncData / AsyncError.
Pattern matching with switch keeps loading/error UI explicit.

Ďalšie kroky

Mutations

Move write operations into provider methods and execute via ref.invoke.

Otvoriť Mutations

Flutter API

Choose between Consumer, ConsumerWidget, and ConsumerStatefulWidget.

Open Flutter API