Step 1 / 4
Providers are declarations
A provider is a global, immutable declaration of how to create a value. The value itself lives in ProviderScope at the root of the app, so it's not a global variable and tests can override it.
Declare providers globally, keep state in a ProviderScope, and handle async data with AsyncValue.
1final counterProvider = NotifierProvider<Counter, int>(Counter.new);23class Counter extends Notifier<int> {4 @override5 int build() => 0;67 void increment() => state++;8}910final userProvider = FutureProvider<User>((ref) async {11 final api = ref.watch(apiProvider);12 return api.fetchUser();13});1415class CounterText extends ConsumerWidget {16 const CounterText({super.key});1718 @override19 Widget build(BuildContext context, WidgetRef ref) {20 final count = ref.watch(counterProvider);21 final user = ref.watch(userProvider);22 return Text(switch (user) {23 AsyncData(:final value) => '${value.name}: $count',24 AsyncError() => 'Could not load user',25 _ => 'Loading...',26 });27 }28}2930void main() => runApp(const ProviderScope(child: MyApp()));
items: 0build ×1ref.watchbuild ×1ref.readbuild ×1ref.readbuild ×1ref.readbuild ×1ref.watchbuild ×1Same split with ref.watch / ref.read. The provider is a global declaration, the state lives in ProviderScope.
A provider is a global, immutable declaration of how to create a value. The value itself lives in ProviderScope at the root of the app, so it's not a global variable and tests can override it.