如何在Flutter项目中不建立package直接使用custom_lint创建自定义规则

在Flutter项目中,我想直接使用custom_lint创建自定义规则,但不想单独建立package。有没有办法直接在项目内配置实现?官方文档提到需要创建独立package,这样对小型项目来说太麻烦了。请问如何在现有工程中直接集成custom_lint规则,同时还能正常触发lint检查?需要修改哪些配置文件?

2 回复

在Flutter项目中,无需创建package,可直接在analysis_options.yaml中添加custom_lint插件:

analyzer:
  plugins:
    - custom_lint

然后在pubspec.yaml中依赖custom_lint_builder,并在lib目录创建lint规则文件即可。

更多关于如何在Flutter项目中不建立package直接使用custom_lint创建自定义规则的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter项目中,可以不创建单独的package,直接在项目中创建自定义lint规则。以下是步骤:

1. 添加依赖

pubspec.yaml 中添加:

dev_dependencies:
  custom_lint: ^0.6.0
  lint_core: ^0.6.0

2. 创建lint规则文件

在项目根目录创建 custom_lint 文件夹,然后创建 custom_lint_rules.dart

// custom_lint/custom_lint_rules.dart
import 'package:custom_lint/custom_lint.dart';
import 'package:lint_core/lint_core.dart';

class AvoidHardcodedColors extends DartLintRule {
  AvoidHardcodedColors() : super(
    code: LintCode(
      name: 'avoid_hardcoded_colors',
      problemMessage: '避免使用硬编码颜色值',
      correctionMessage: '请使用主题颜色或定义颜色常量',
      errorSeverity: ErrorSeverity.warning,
    ),
  );

  @override
  void run(
    CustomLintResolver resolver,
    CustomLintReporter reporter,
    CustomLintContext context,
  ) {
    context.registry.addInstanceCreationExpression((node) {
      final constructorName = node.constructorName.toString();
      if (constructorName.contains('Color') && 
          node.argumentList.arguments.any((arg) => 
            arg is IntegerLiteral && arg.literal.value > 0xFF000000)) {
        reporter.reportErrorForNode(code, node);
      }
    });
  }
}

3. 创建lint插件

custom_lint 文件夹中创建 custom_lint_plugin.dart

// custom_lint/custom_lint_plugin.dart
import 'package:custom_lint/custom_lint.dart';
import 'custom_lint_rules.dart';

PluginBase createPlugin() => _CustomLintPlugin();

class _CustomLintPlugin extends PluginBase {
  @override
  List<LintRule> getLintRules(CustomLintConfigs configs) {
    return [
      AvoidHardcodedColors(),
    ];
  }
}

4. 配置analysis_options.yaml

在项目根目录的 analysis_options.yaml 中添加:

analyzer:
  plugins:
    - custom_lint

5. 启用lint规则

创建 custom_lint.yaml 文件:

rules:
  - avoid_hardcoded_colors

使用说明

  • 运行 flutter pub get 安装依赖
  • IDE需要重启以加载自定义lint规则
  • 规则会在代码分析时自动执行

这种方式避免了创建单独的package,直接在项目中管理自定义lint规则。

回到顶部