watch<StateT> abstract method
StateT
watch<StateT>(
- ProviderListenable<
StateT> provider
Returns the value exposed by a provider and rebuild the widget when that value changes.
This method should only be used at the "root" of the build
method of a widget.
Good: Use watch inside the build
method.
class Example extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
// Correct, we are inside the build method and at its root.
final count = ref.watch(counterProvider);
}
}
Good: It is accepted to use watch at the root of "builders" too.
class Example extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return ListView.builder(
itemBuilder: (context) {
// This is accepted, as we are at the root of a "builder"
final count = ref.watch(counterProvider);
},
);
}
}
Bad: Don't use watch outside of the build
method.
class Example extends ConsumerStatefulWidget {
@override
ExampleState createState() => ExampleState();
}
class ExampleState extends ConsumerState<Example> {
@override
void initState() {
super.initState();
// Incorrect, we are not inside the build method.
final count = ref.watch(counterProvider);
}
}
Bad: Don't use watch inside event handles withing build
method.
class Example extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return ElevatedButton(
onTap: () {
// Incorrect, we are inside the build method, but neither at its
// root, nor inside a "builder".
final count = ref.watch(counterProvider);
}
);
}
}
See also:
- ProviderListenableSelect.select, which allows a widget to filter rebuilds by observing only the selected properties.
- listen, to react to changes on a provider, such as for showing modals.
Implementation
StateT watch<StateT>(ProviderListenable<StateT> provider);