WidgetRef
(ref) is used to access any provider in our codebase (as long as we import the corresponding file). This is done by design because all Riverpod providers are global.
Definition of providers:
final idProvider = StateProvider<String>((ref) => '-'); final SwitchProvider = StateProvider<bool>((ref) => Auth.switchOn); final profileProvider = FutureProvider.autoDispose<List>( (ref) => getProfile(id: ref.read(idProvider)), );
Wait for data from a FutureProvider:
List profile = await ref.read(profileProvider.future);
Listen to a provider:
ref.listen<bool>(switchProvider, (var previousvalue, var newvalue) { print('The switch changed from $previousvalue to $newvalue'); });
Update the state of the provider with a new value:
StateController<int> counter = ref.read(counterProvider.notifier); counter.state++, ref.read(switchProvider.notifier).state = value
Watch in widget:
ref.watch(profileProvider).when( data: (data) => showProfiles(data), error: (e, stack) => Text(e.toString()), loading: () => const Center( child: CircularProgressIndicator(), ), ),
Reset provider:
ref.refresh(counterProvider);
Consumer structure:
Consumer( builder: (BuildContext context, WidgetRef ref, Widget? _) { return Widget_with_access_to_context_and_ref; } )
Sources:
https://codewithandrea.com/articles/flutter-state-management-riverpod
https://riverpod.dev/docs/concepts/reading