Providers

Provider gives synchronous state. AsyncProvider returns AsyncValue y can expose Future y Stream con strict lifecycle handling.

Provider tipos

Choose provider type by data source y update frequency.

Provider<T>

Synchronous values y local derived state

AsyncProvider<T>

Future/Stream-driven state as AsyncValue<T>

provider.future

Selector that exposes Provider<Future<T>>

Tip

If state comes de network o stream, prefer AsyncProvider first. Keep Provider para pure synchronous logic.

Read API Matrix

Use watch en build paths, read para one-shot access, y listen para 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 y Stream con AsyncProvider

A single AsyncProvider can return a Future o 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, y dispose.
AsyncValue is a sealed class: AsyncLoading / AsyncData / AsyncError.
Pattern matching con switch keeps loading/error UI explicit.

Siguientes pasos

Mutations

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

Open mutaciones

Flutter API

Choose between Consumer, ConsumerWidget, y ConsumerStatefulWidget.

Open Flutter API