请教如何为Flutter与Dart定义自定义Linter规则
Hey there! Let's walk through how to set up linter rules for your Flutter/Dart projects, plus how to build your own custom rules when the predefined ones don't cut it. I'll keep this practical with examples you can copy-paste and tweak.
Getting started with existing rules is super straightforward—here's how:
Add the lint package dependency
Flutter and Dart maintain official lint packages with curated rule sets. Add the relevant one to yourpubspec.yamlunderdev_dependencies:dev_dependencies: # For Flutter projects flutter_lints: ^2.0.0 # For pure Dart projects lints: ^2.0.0Run
flutter pub getordart pub getto install it.Create/modify the analysis_options.yaml file
This file is where you'll control which rules are enabled or disabled. Start by inheriting the default rule set, then customize as needed:# Inherit the default Flutter lint rules include: package:flutter_lints/flutter.yaml linter: rules: # Enable a specific rule that's off by default prefer_const_constructors: true # Disable a rule from the default set avoid_print: false # You can also set rules with options (if supported) prefer_single_quotes: trueRun the linter
Check your code manually with the command line:# For Flutter flutter analyze # For pure Dart dart analyzeMost IDEs (like VS Code or Android Studio) will also show lint warnings in real-time as you code.
If you need to enforce project-specific standards (like banning certain functions or enforcing naming conventions), you can build your own rules. We'll use the custom_lint_builder package to simplify this process:
Set up a custom lint package
Custom rules live in a separate Dart package (not your Flutter app). Create one with:dart create -t package my_custom_lints cd my_custom_lintsAdd these dependencies to
pubspec.yaml:dependencies: analyzer: ^5.13.0 custom_lint_builder: ^0.6.0 dev_dependencies: test: ^1.24.0 custom_lint: ^0.6.0Write your custom rule
Create a filelib/src/no_print_rule.dartfor a rule that bansprint()calls (encouraging logging libraries instead):import 'package:analyzer/dart/ast/ast.dart'; import 'package:custom_lint_builder/custom_lint_builder.dart'; class NoPrintRule extends DartLintRule { NoPrintRule() : super( code: const LintCode( name: 'no_print', problemMessage: 'Avoid using print()—use a logging library like logger instead.', correctionMessage: 'Replace print(...) with Logger().d(...) or similar.', ), ); @override void run( CustomLintResolver resolver, ErrorReporter reporter, CustomLintContext context, ) { // Listen for method invocations in the code context.registry.addMethodInvocation((node) { // Check if the method is a top-level print() call if (node.methodName.name == 'print' && node.target == null) { // Report an error at the print() call location reporter.reportErrorForNode(code, node); } }); } }Register your rule
Updatelib/my_custom_lints.dartto register your rule with the linter plugin:import 'package:custom_lint_builder/custom_lint_builder.dart'; import 'src/no_print_rule.dart'; PluginBase createPlugin() => _MyCustomLints(); class _MyCustomLints extends PluginBase { @override List<DartLintRule> getLintRules(CustomLintConfigs configs) => [ NoPrintRule(), // Add more rules here later ]; }Use the custom rule in your project
Go back to your Flutter/Dart project and add the custom lint package topubspec.yaml:dev_dependencies: flutter_lints: ^2.0.0 my_custom_lints: path: ../my_custom_lints # Use path if local, or pub.dev package name if publishedThen update
analysis_options.yamlto enable the rule:include: package:flutter_lints/flutter.yaml linter: rules: my_custom_lints/no_print: trueRun
flutter analyze—you'll now see warnings whereverprint()is used!Test your rule
Write tests to make sure your rule works as expected. Createtest/no_print_rule_test.dart:import 'package:custom_lint_test/custom_lint_test.dart'; import 'package:test/test.dart'; void main() { test('Detects print() calls', () async { await resolveSource(''' void main() { print('hello'); // LINT } ''').expectLints(['no_print']); }); test('Ignores print() from a class', () async { await resolveSource(''' class Logger { void print(String msg) {} } void main() { Logger().print('hello'); // NO LINT } ''').expectNoLints(); }); }Run tests with
dart test.
内容的提问来源于stack exchange,提问作者Hamed Rezaee

