Skip to main content

avoid-hooks-outside-build

added in: 1.12.0
⚙️
Pro+

Warns when a hook is used outside the build method, other hooks or HookBuilder.

⚙️ Config

Set additional-methods (default is empty) to allow additional methods to call hooks (not only build) (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-hooks-outside-build:
additional-methods:
- customBuild

Example

❌ Bad:

class MyWidget extends HookWidget {
void myCallback() {
useMemoized(() => null); // LINT: Avoid hooks outside of the 'build' method or other hooks.
}


Widget build(BuildContext context) {
return FloatingActionButton(onPressed: () {
useMemoized(() {}); // LINT: Avoid hooks outside of the 'build' method or other hooks.
});
}
}

✅ Good:

class MyWidget extends HookWidget {

Widget build(BuildContext context) {
useMemoized(() {});

return FloatingActionButton(onPressed: () {
...
});
}

void _useMyHook() {
useMemoized(() => null);
}
}

Example with "additional-methods"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-hooks-outside-build:
additional-methods:
- customBuild

✅ Good:

class MyWidget extends SomeHookWidget {

Widget customBuild(BuildContext context) {
useMemoized(() { ... }); // Correct, 'customBuild' is allowed to call hooks
}
}