avoid-watch-outside-build
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) {
// LINT: Avoid using 'watch' outside of the 'build' method. Try rewriting the code to use 'read' instead.
final value = context.watch<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: () {
// LINT: Avoid using 'watch' outside of the 'build' method. Try rewriting the code to use 'read' instead.
context.watch<String>();
}),
],
),
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>(),
),
);
}
}