avoid-ref-watch-outside-build
Warns when ref.watch
is used outside of the build
method.
ref.watch
is designed to subscribe to changes which is not needed when the value is red outside of the build
method.
Example
❌ Bad:
class HomeConsumerWidget extends ConsumerWidget {
const HomeConsumerWidget();
void callback(WidgetRef ref) {
final value = ref.watch(counterProvider); // LINT
}
Widget build(BuildContext context, WidgetRef ref) {
final counter = ref.watch(counterProvider);
return Text('$counter');
}
}
✅ Good:
class HomeConsumerWidget extends ConsumerWidget {
const HomeConsumerWidget();
void callback(WidgetRef ref) {
final value = ref.read(counterProvider);
}
Widget build(BuildContext context, WidgetRef ref) {
final counter = ref.watch(counterProvider);
return Text('$counter');
}
}