flutter_hooks_lint_plugin

flutter_hooks_lint_plugin is a dart analyzer plugin for the flutter hooks, inspired by eslint-plugin-react-hooks.

Rules

Missing/Unnecessary keys

Lint to detect missing, unnecessary keys in the useEffect calling.
It finds build variables (class fields, local variables, any other build-related variables) in the HookWidget, then compares references of the build variables and specified keys in the useEffect calling, and reports a lint error if there are any differences.

final variable1 = callSomething();
final variable2 = callSomething();

useEffect(() {
  print(variable1);
}, [variable2]); // <= missing key 'variable1', unnecessary key 'variable2'

Avoid nested using of hooks

Lint to detect nested using of hooks which is one of the bad practices.
It reports a lint error if there are any using of hooks under control flow syntax (if, for, while, ... ).

if (flag) {
  final variable = useState('hello'); // <= avoid nested hooks
}

Installation

Add flutter_hooks_lint_plugin dependency to your pubspec.yaml:

dev_dependencies:
  flutter_hooks_lint_plugin: ^0.7.0

Add flutter_hooks_lint_plugin plugin directive to your analyzer_options.yaml:

plugins:
  flutter_hooks_lint_plugin:
    diagnostics:
      exhaustive_keys: true
      nested_hooks: true

Then, run flutter pub get and restart your IDE/Editor.

Options

You can customize plugin's behavior by the analysis_options.yaml:

flutter_hooks_lint_plugin:
  exhaustive_keys:
    # hooks do not change over the state's lifecycle 
    constant_hooks:
      # default values
      - useRef
      - useIsMounted
      - useFocusNode
      - useContext

      # your custom hooks here
      - useConstantValue

Suppress lints

There are several ways to suppress lints:

  1. add // ignore_for_file: exhaustive_keys.missing_key, rules_of_hooks.nested_hooks to suppress lints in the entire file
  2. add // ignore: exhaustive_keys.missing_key, rules_of_hooks.nested_hooks to suppress lints at the next or current line
  3. add // ignore_keys: foo, bar to suppress lints for the specific keys at the next or current line

Contribution

Welcome PRs!

LICENSE

The MIT License © mjhd

Libraries

main