Writing custom lint rules with analyzer plugins

suggest change

Dart 3.10 added a new analyzer plugin system. A plugin is an ordinary Dart package that adds your own lint rules, warnings and quick fixes to the Dart analyzer. The diagnostics show up in VS Code and IntelliJ, and also in dart analyze and flutter analyze, so you can enforce project-specific rules in CI.

This article builds a plugin with one rule: avoid_datetime_now reports calls to DateTime.now() and offers a quick fix that replaces them with clock.now() from package:clock, so tests can control the time. It covers:

For dart format, the standard lint sets and a stricter analysis_options.yaml, see Coding conventions.

All output below is from Dart 3.13.4 with analysis_server_plugin 0.3.24 and analyzer 14.5.0.

Old and new plugin systems

Dart has had analyzer plugins since 2018, but the old API (package:analyzer_plugin, enabled under analyzer: plugins:) was hard to use, and most people used the third-party custom_lint package instead. The new system is built into the analysis server:

The legacy system was deprecated in Dart 3.13.2. Write new plugins with the new API.

The project layout

We'll use two packages next to each other: the plugin, and an app that uses it.

clock_lints/                     <- the plugin package
├── pubspec.yaml
├── lib/
│   ├── main.dart                <- required entry point
│   └── src/
│       ├── avoid_datetime_now.dart   <- the rule
│       └── use_clock_now.dart        <- the quick fix
└── test/
    └── avoid_datetime_now_test.dart
app/                             <- a package that uses the plugin
├── pubspec.yaml
├── analysis_options.yaml
└── lib/session.dart

The plugin's pubspec

name: clock_lints
description: Lint rules that keep DateTime.now() out of our code.
version: 1.0.0
publish_to: none

environment:
  sdk: ^3.10.0

dependencies:
  analysis_server_plugin: ^0.3.24
  analyzer: ^14.5.0

dev_dependencies:
  analyzer_testing: ^0.4.3
  test: ^1.26.0
  test_reflective_loader: ^0.6.0

analysis_server_plugin, analyzer, analyzer_plugin and analyzer_testing are released together from the SDK repository, and each version pins exact versions of the others (analysis_server_plugin 0.3.24 requires exactly analyzer 14.5.0). If you get a version-solving error, pick the analyzer version that your analysis_server_plugin and analyzer_testing versions require.

You don't control the final versions, though. When the analysis server loads plugins, it generates its own package that depends on your plugin and on analysis_server_plugin with a constraint chosen by the SDK (^0.3.8 in Dart 3.13), and runs dart pub upgrade on it. So don't constrain these packages more tightly than you have to.

The entry point: lib/main.dart

The analysis server imports lib/main.dart from your plugin and reads a top-level variable named plugin:

import 'package:analysis_server_plugin/plugin.dart';
import 'package:analysis_server_plugin/registry.dart';

import 'src/avoid_datetime_now.dart';
import 'src/use_clock_now.dart';

final plugin = ClockLintsPlugin();

class ClockLintsPlugin extends Plugin {
  @override
  String get name => 'clock_lints';

  @override
  void register(PluginRegistry registry) {
    registry.registerLintRule(AvoidDateTimeNow());
    registry.registerFixForRule(AvoidDateTimeNow.code, UseClockNow.new);
  }
}

In register you add what the plugin provides:

Writing the rule

A rule has two parts: a class that extends AnalysisRule and describes the rule, and a visitor that walks the syntax tree and reports problems.

import 'package:analyzer/analysis_rule/analysis_rule.dart';
import 'package:analyzer/analysis_rule/rule_context.dart';
import 'package:analyzer/analysis_rule/rule_visitor_registry.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/error/error.dart';

class AvoidDateTimeNow extends AnalysisRule {
  static const LintCode code = LintCode(
    'avoid_datetime_now',
    "Don't call 'DateTime.now()' directly.",
    correctionMessage: "Try using 'clock.now()' from package:clock.",
  );

  AvoidDateTimeNow()
    : super(
        name: 'avoid_datetime_now',
        description: 'Use clock.now() so that tests can control the time.',
      );

  @override
  LintCode get diagnosticCode => code;

  @override
  void registerNodeProcessors(
    RuleVisitorRegistry registry,
    RuleContext context,
  ) {
    var visitor = _Visitor(this, context);
    registry.addInstanceCreationExpression(this, visitor);
  }
}

class _Visitor extends SimpleAstVisitor<void> {
  final AnalysisRule rule;
  final RuleContext context;

  _Visitor(this.rule, this.context);

  @override
  void visitInstanceCreationExpression(InstanceCreationExpression node) {
    // Tests may use the real clock.
    if (context.isInTestDirectory) return;

    var constructor = node.constructorName.element;
    if (constructor == null) return; // unresolved code
    if (constructor.name != 'now') return;

    var cls = constructor.enclosingElement;
    if (cls.name == 'DateTime' && cls.library.isDartCore) {
      rule.reportAtNode(node);
    }
  }
}

What each piece does:

The rule works on the resolved AST, so it can check what the code means, not just how it looks. DateTime.now() parses as a method call, but after resolution the analyzer rewrites it into an InstanceCreationExpression whose constructorName.element is the now constructor. We check that the constructor belongs to the DateTime class from dart:core, so a class of your own that happens to be called DateTime isn't reported.

RuleContext tells you about the file being analyzed: isInLibDir, isInTestDirectory, package, libraryElement, typeProvider, typeSystem and isFeatureEnabled(...). To report a problem, call one of the reportAt... methods: reportAtNode, reportAtToken, reportAtOffset or reportAtSourceRange. If the messages contain {0}, {1} placeholders, pass the values in arguments:.

If one rule needs several messages, extend MultiAnalysisRule instead, return all codes from diagnosticCodes, and pass diagnosticCode: to each reportAt... call.

Adding a quick fix

A quick fix extends ResolvedCorrectionProducer. It gets the node that the diagnostic was reported on and builds a set of edits:

import 'package:analysis_server_plugin/edit/change_builder/change_builder.dart';
import 'package:analysis_server_plugin/edit/dart/correction_producer.dart';
import 'package:analysis_server_plugin/edit/dart/dart_fix_kind_priority.dart';
import 'package:analysis_server_plugin/edit/fix/fix.dart';
import 'package:analysis_server_plugin/edit/range_factory.dart';
import 'package:analyzer/dart/ast/ast.dart';

class UseClockNow extends ResolvedCorrectionProducer {
  static const _kind = FixKind(
    'clock_lints.fix.useClockNow',
    DartFixKindPriority.standard,
    "Replace with 'clock.now()'",
  );

  UseClockNow({required super.context});

  @override
  CorrectionApplicability get applicability =>
      CorrectionApplicability.singleLocation;

  @override
  FixKind get fixKind => _kind;

  @override
  Future<void> compute(ChangeBuilder builder) async {
    var creation = node;
    if (creation is! InstanceCreationExpression) return;

    await builder.addDartFileEdit(file, (builder) {
      var result = builder.importLibraryElement(
        Uri.parse('package:clock/clock.dart'),
      );
      var prefix = result.prefix;
      var clock = prefix == null ? 'clock' : '$prefix.clock';
      builder.addSimpleReplacement(range.node(creation), '$clock.now()');
    });
  }
}

Since version 0.3.17, analysis_server_plugin re-exports ChangeBuilder, FixKind and range from package:analyzer_plugin, so the plugin doesn't need to depend on analyzer_plugin itself.

Enabling the plugin

In the package that should be checked, add a top-level plugins: section to analysis_options.yaml. Note that it's at the top level, not under analyzer: like the legacy plugins:

include: package:lints/recommended.yaml

plugins:
  clock_lints:
    path: ../clock_lints
    diagnostics:
      avoid_datetime_now: true

The value after the plugin name works like a dependency in pubspec.yaml. Besides path: (relative or absolute), it can be a version constraint for a package on pub.dev, or a git source:

plugins:
  clock_lints: ^1.0.0
plugins:
  clock_lints:
    git:
      url: https://github.com/acme/clock_lints.git
      ref: v1.0.0

The plugin doesn't go into the app's pubspec.yaml. The analysis server resolves it on its own.

Lints are listed under diagnostics:. A value of true enables the lint, false disables it (useful if an included options file turned it on), and info, warning or error enable it with that severity. Plugins can only be configured in the analysis_options.yaml file at the root of a package or pub workspace, not in nested options files.

Here is the code we want to catch, app/lib/session.dart:

class Session {
  final DateTime expiresAt;

  Session(Duration ttl) : expiresAt = DateTime.now().add(ttl);

  bool get isExpired => DateTime.now().isAfter(expiresAt);
}

and app/bin/app.dart:

import 'package:app/session.dart';

void main() {
  var session = Session(const Duration(minutes: 30));
  print('started at ${DateTime.now()}, expired: ${session.isExpired}');
}

Run dart analyze:

$ dart analyze
Analyzing app...

   info - bin\app.dart:5:23 - Don't call 'DateTime.now()' directly. Try using 'clock.now()' from package:clock. - avoid_datetime_now
   info - lib\session.dart:4:39 - Don't call 'DateTime.now()' directly. Try using 'clock.now()' from package:clock. - avoid_datetime_now
   info - lib\session.dart:6:25 - Don't call 'DateTime.now()' directly. Try using 'clock.now()' from package:clock. - avoid_datetime_now

3 issues found.

The first run took about 40 seconds, because the server resolved the plugin's dependencies and compiled it to an AOT snapshot. Since Dart 3.12 the snapshot is reused, so the next run took 2 seconds. The server recompiles the plugin when its source changes.

After you change the plugins: section, restart the analysis server in your IDE ("Dart: Restart Analysis Server" in VS Code). dart analyze starts a new server each time, so it always sees the latest settings.

Suppressing a diagnostic

Plugin diagnostics are suppressed like built-in ones, but the code is prefixed with the plugin name:

import 'package:app/session.dart';

void main() {
  var session = Session(const Duration(minutes: 30));
  // Printing the wall-clock time is fine here.
  // ignore: clock_lints/avoid_datetime_now
  print('started at ${DateTime.now()}, expired: ${session.isExpired}');
}

// ignore_for_file: clock_lints/avoid_datetime_now works for a whole file.

Making the rule fail the build

Lints are reported as info by default, and dart analyze only fails on infos with --fatal-infos. To make the rule an error, set the severity under diagnostics::

plugins:
  clock_lints:
    path: ../clock_lints
    diagnostics:
      avoid_datetime_now: error
$ dart analyze
Analyzing app...

  error - lib\session.dart:4:39 - Don't call 'DateTime.now()' directly. Try using 'clock.now()' from package:clock. - avoid_datetime_now
  error - lib\session.dart:6:25 - Don't call 'DateTime.now()' directly. Try using 'clock.now()' from package:clock. - avoid_datetime_now

2 issues found.

The exit code is 3 for errors, 2 for warnings and 1 for infos with --fatal-infos. Setting the severity under analyzer: errors: doesn't work for plugin diagnostics: the analyzer reports 'clock_lints/avoid_datetime_now' isn't a recognized diagnostic code.

The quick fix in the IDE

In the editor, the lightbulb on DateTime.now() offers the plugin's fix, followed by the standard "ignore" fixes that the server adds for every diagnostic. This is what the analysis server returned for an edit.getFixes request at the first DateTime.now() in session.dart:

Replace with 'clock.now()'
  {'offset': 83, 'length': 14, 'replacement': 'clock.now()'}
  {'offset': 0, 'length': 0, 'replacement': "import 'package:clock/clock.dart';\n\n"}
Ignore 'clock_lints/avoid_datetime_now' for this line
Ignore 'clock_lints/avoid_datetime_now' for the whole file
Ignore 'clock_lints/avoid_datetime_now' in `analysis_options.yaml`

dart fix --apply doesn't apply plugin fixes yet; it prints Nothing to fix!.

After applying the fix (and adding clock to the app's dependencies), the class can be tested at any point in time:

import 'package:clock/clock.dart';

class Session {
  final DateTime expiresAt;

  Session(Duration ttl) : expiresAt = clock.now().add(ttl);

  bool get isExpired => clock.now().isAfter(expiresAt);
}
import 'package:app/session.dart';
import 'package:clock/clock.dart';
import 'package:test/test.dart';

void main() {
  test('session expires after its ttl', () {
    var start = DateTime(2026, 10, 18, 12);
    var session = withClock(
      Clock.fixed(start),
      () => Session(const Duration(minutes: 30)),
    );

    withClock(Clock.fixed(start.add(const Duration(minutes: 29))), () {
      expect(session.isExpired, isFalse);
    });
    withClock(Clock.fixed(start.add(const Duration(minutes: 31))), () {
      expect(session.isExpired, isTrue);
    });
  });
}
$ dart test
00:00 +0: test\session_test.dart: session expires after its ttl
00:00 +1: All tests passed!

Testing the rule

Starting the analysis server for every change is slow. package:analyzer_testing runs a rule against snippets of code in memory. Tests are classes based on package:test_reflective_loader: every method whose name starts with test_ is a test case.

import 'package:analyzer_testing/analysis_rule/analysis_rule.dart';
import 'package:clock_lints/src/avoid_datetime_now.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';

void main() {
  defineReflectiveSuite(() {
    defineReflectiveTests(AvoidDateTimeNowTest);
  });
}

@reflectiveTest
class AvoidDateTimeNowTest extends AnalysisRuleTest {
  @override
  void setUp() {
    rule = AvoidDateTimeNow();
    super.setUp();
  }

  Future<void> test_now() async {
    await assertDiagnostics(
      r'''
var t = DateTime.now();
''',
      [lint(8, 14)],
    );
  }

  Future<void> test_nowWithNew() async {
    await assertDiagnostics(
      r'''
var t = new DateTime.now();
''',
      [lint(8, 18)],
    );
  }

  Future<void> test_inTestDirectory() async {
    var path = '$testPackageRootPath/test/clock_test.dart';
    newFile(path, r'''
var t = DateTime.now();
''');
    await assertNoDiagnosticsInFile(path);
  }

  Future<void> test_otherClassNamedDateTime() async {
    await assertNoDiagnostics(r'''
class DateTime {
  DateTime.now();
}
var t = DateTime.now();
''');
  }
}
$ dart test
00:00 +0: loading test\avoid_datetime_now_test.dart
00:00 +0: test\avoid_datetime_now_test.dart: AvoidDateTimeNowTest test_now
00:02 +1: test\avoid_datetime_now_test.dart: AvoidDateTimeNowTest test_nowWithNew
00:02 +2: test\avoid_datetime_now_test.dart: AvoidDateTimeNowTest test_inTestDirectory
00:02 +3: test\avoid_datetime_now_test.dart: AvoidDateTimeNowTest test_otherClassNamedDateTime
00:03 +4: All tests passed!

If a test fails, the message shows what was actually reported. This is test_inTestDirectory failing after removing the isInTestDirectory check from the visitor:

Found but did not expect:
  avoid_datetime_now.avoid_datetime_now [8, 14, Don't call 'DateTime.now()' directly., "Try using 'clock.now()' from package:clock."]

The tests run against a small mock SDK, not the real dart:core. Its DateTime only has now(), compareTo, isBefore and millisecondsSinceEpoch. A test that uses DateTime.utc(...) fails with The method 'utc' isn't defined for the type 'DateTime'. If your rule looks at types from other packages, write small stubs of them with newPackage('name')..addFile('lib/name.dart', '...') in setUp, before super.setUp().

Plugins run in an isolate inside the analysis server, and its stdout carries the protocol messages, so print can't write to the terminal. Since Dart 3.12, print calls made while a rule runs are collected by the server and shown on the Plugins page of the analysis server's Insights pages. Add a print to the visitor:

  @override
  void visitInstanceCreationExpression(InstanceCreationExpression node) {
    print('visiting ${node.toSource()} in ${context.currentUnit?.file.path}');
    // ...
  }

To open the Insights pages in VS Code, run the Dart extension's "Open Analyzer Diagnostics" command (newer versions call the pages Insights). You can also start the server with --diagnostic-port=<port> and open http://localhost:<port>/plugins. The page shows where the plugin was built, what it registered, and the debug output:

Bootstrap package path:
C:\Users\kjk\AppData\Local\Temp\pbw-lintplug\cache\.plugin_manager\bbd6f4d8321a3accda49ebdce4c0ffec
Associated contexts:
C:\Users\kjk\AppData\Local\Temp\pbw-lintplug\app
clock_lints
Debug print output:
2026-10-18 00:55:36.668: visiting Session(const Duration(minutes: 30)) in C:\Users\kjk\AppData\Local\Temp\pbw-lintplug\app\bin\app.dart
2026-10-18 00:55:36.668: visiting const Duration(minutes: 30) in C:\Users\kjk\AppData\Local\Temp\pbw-lintplug\app\bin\app.dart
2026-10-18 00:55:36.668: visiting DateTime.now() in C:\Users\kjk\AppData\Local\Temp\pbw-lintplug\app\bin\app.dart
2026-10-18 00:55:36.669: visiting DateTime.now() in C:\Users\kjk\AppData\Local\Temp\pbw-lintplug\app\lib\session.dart
2026-10-18 00:55:36.669: visiting DateTime.now() in C:\Users\kjk\AppData\Local\Temp\pbw-lintplug\app\lib\session.dart
Lint rules:
avoid_datetime_now
Quick fixes:
clock_lints.fix.useClockNow: "Replace with 'clock.now()'" to fix avoid_datetime_now

The visitor also runs for Session(...) and Duration(...), because it's registered for every instance creation. That's why the rule checks the constructor before reporting anything. If the plugin crashes, the same page shows the exception. It's also the first place to look when a rule silently reports nothing.

The Bootstrap package path is the package the server generated for the plugins. Its pubspec.yaml lists analysis_server_plugin: ^0.3.8 and your plugin. It's stored under .plugin_manager in the analysis server's cache directory (a .dartServer directory by default; dart analyze --cache=<dir> moves it, which is what the paths above show).

Running plugins in CI

dart analyze runs plugins, so CI only needs the usual steps (see Testing in CI). If the plugin lives in the same repository, run its tests too:

name: analyze
on: [push, pull_request]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dart-lang/setup-dart@v1
        with:
          sdk: 3.13.4
      - name: Test the lint plugin
        working-directory: clock_lints
        run: |
          dart pub get
          dart test
      - name: Analyze the app
        working-directory: app
        run: |
          dart pub get
          dart analyze --fatal-infos

Things to keep in mind:

New built-in lints worth enabling

Before you write a plugin, check that a built-in lint doesn't already do the job. Recent SDKs added a few that aren't in package:lints yet:

include: package:lints/recommended.yaml

linter:
  rules:
    - switch_on_type
    - unnecessary_unawaited
    - no_dynamic_casts
import 'dart:async';
import 'dart:convert';

import 'package:meta/meta.dart';

String describe(Object value) => switch (value.runtimeType) {
  const (int) => 'an int',
  const (String) => 'a string',
  _ => 'something else',
};

@awaitNotRequired
Future<void> logEvent(String event) async {}

void main() {
  unawaited(logEvent('start'));
  var data = jsonDecode('{"name": "Ann"}');
  String name = data['name'];
  print('${describe(1)} $name');
}
$ dart analyze
Analyzing newlints...

   info - lib\demo.dart:6:42 - Avoid switch statements on a 'Type'. Try using pattern matching on a variable instead. - switch_on_type
   info - lib\demo.dart:16:3 - Unnecessary use of 'unawaited'. Try removing the use of 'unawaited', as the unawaited element is annotated with '@awaitNotRequired'. - unnecessary_unawaited
   info - lib\demo.dart:18:17 - Implicit cast from 'dynamic'. Try adding an explicit cast or changing the target type. - no_dynamic_casts

3 issues found.

Dart 3.13 also deprecated two built-in lints, avoid_private_typedef_functions and one_member_abstracts. If your team relies on them, the SDK suggests re-implementing them as plugin rules.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents