Skip to main content

avoid-watch-outside-build

added in: 1.4.0

Warns when a watch or select methods are used outside of the build method.

watch is designed to subscribe to changes which is not needed when the value is red outside of the build method.

Example

❌ Bad:

class MyHomePage extends StatelessWidget {
const MyHomePage();

void callback(BuildContext context) {
final value = context.watch<String>(); // LINT
}


Widget build(BuildContext context) {
final value = context.watch<String>();

return Scaffold(
body: Column(
children: [
Text('You have pushed the button this many times:'),
FloatingActionButton(onPressed: () {
context.watch<String>(); // LINT
}),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<String>(),
),
);
}
}

✅ Good:

class MyHomePage extends StatelessWidget {
const MyHomePage();

void callback(BuildContext context) {
final value = context.read<String>();
}


Widget build(BuildContext context) {
final value = context.watch<String>();

return Scaffold(
body: Column(
children: [
Text('You have pushed the button this many times:'),
FloatingActionButton(onPressed: () {
context.read<String>();
}),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<String>(),
),
);
}
}