Skip to main content

avoid-ref-watch-outside-build

added in: 1.17.0
Pro+

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');
}
}