CodeBlanks Logo Icon CodeBlanks

Custom lint

Learn to write custom lint rules.

Custom lint

custom_lint is a package that lets you write custom lint rules. It is built on the analyzer; each rule inspects an AST node.

A lint rule extends the LintRule class: name (rule name), message (warning text) and a run method (check logic).

Run it with dart pub run custom_lint. Rules walk all files in the project and report violations. An IDE plugin makes them work in real time.

Rule declaration

A lint rule declares these parts: name (unique identifier, e.g. avoid_print), message (violation text) and a run method.

The run method takes a ResolvedUnitResult (resolved source). Inside it you walk the AST and call reporter.reportError(...) on violations.

Rules are gathered in a plugin: class MyPlugin extends PluginLintPlugin. The plugin is enabled via analysis_options.yaml.

Practice Define a LintRule skeleton

Define a LintRule class with final String name; and final String message; fields, a LintRule(this.name, this.message); constructor and a void report() => print('[$name] $message'); method. In main create final rule = LintRule('avoid_print', 'do not use print()'); and call rule.report();.

Starter code

main.dart
void main() {
  // define a LintRule class (name, message fields; report method)
  // create a rule; call report
}

Sample solution

main.dart
class LintRule {
  final String name;
  final String message;
  LintRule(this.name, this.message);
  void report() => print('[$name] $message');
}

void main() {
  final rule = LintRule('avoid_print', 'do not use print()');
  rule.report();
}

Expected output

[avoid_print] do not use print()

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 LintRule inheritance

Question
class AvoidPrintRule extends ____ { }
Answer
class AvoidPrintRule extends LintRule { }

Explanation: every custom lint rule extends the LintRule class.

2 Match the lint rule parts

Term Meaning
LintRule Rule base
name Rule name
message Warning text
AstVisitor Node visit

3 What does a custom_lint rule extend?

  • LintPlugin
  • LintRule Correct answer
  • Diagnostic
  • AnalyzerConfig

Explanation: every rule extends the LintRule class.

All lessons in Expert