介绍 package:flutter_lints
概述
#package:flutter_lints
定义了最新的推荐 lint 集合,鼓励 Flutter 应用、包和插件遵循良好的编码实践。使用 Flutter 2.5 或更新版本通过 flutter create
创建的项目已启用最新的推荐 lint 集合。早于该版本的项目可以通过本指南中的说明进行升级。
背景
#在引入 package:flutter_lints
之前,Flutter 框架自带了一组在 analysis_options_user.yaml
中定义的 lint,如果 Flutter 项目没有定义自定义 analysis_options.yaml
文件,则由 dart analyzer 使用它来识别代码问题。由于 analysis_options_user.yaml
与特定框架版本绑定,因此很难在不破坏现有应用、包和插件的情况下进行演进。因此,analysis_options_user.yaml
中定义的 lint 已严重过时。为了解决这个问题,创建了 package:flutter_lints
。该包对 lint 集合进行版本控制,使其能够在不破坏现有项目的情况下进行演进。由于该包建立在 Dart 的 package:lints
之上,因此也使推荐给 Flutter 项目的 lint 与 Dart 生态系统的其余部分保持一致。
迁移指南
#请按照以下步骤将您的 Flutter 项目迁移到使用 package:flutter_lints
的最新推荐 lint。
通过在项目根目录下运行 flutter pub add --dev flutter_lints
,将 package:flutter_lints
添加到您项目的 pubspec.yaml
文件中作为开发依赖项。
在项目根目录下(与 pubspec.yaml
文件相邻)创建一个 analysis_options.yaml
文件,内容如下:
include: package:flutter_lints/flutter.yaml
新激活的 lint 集合可能会在您的代码中识别出一些新问题。要找到它们,请在支持 Dart 的 IDE 中打开您的项目,或在命令行中运行 flutter analyze
。您可以通过在项目根目录下运行 dart fix --apply
来自动修复其中一些报告的问题。
现有的自定义 analysis_options.yaml 文件
#如果您的项目根目录下已有一个自定义的 analysis_options.yaml
文件,请在文件顶部添加 include: package:flutter_lints/flutter.yaml
来激活 package:flutter_lints
的 lint。如果您的 analysis_options.yaml
已包含 include:
指令,您必须决定是保留那些 lint 还是用 package:flutter_lints
的 lint 替换它们,因为 Dart analyzer 每个 analysis_options.yaml
文件只支持一个 include:
指令。
自定义 lint
#给定项目激活的 lint 可以在 analysis_options.yaml
文件中进一步自定义。以下示例文件展示了这一点,该文件是 flutter create
为新项目生成的 analysis_options.yaml
文件的重现。
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.ac.cn/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at
# https://dart-lang.github.io/linter/lints/index.html.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.ac.cn/guides/language/analysis-options
时间线
#发布于版本:2.3.0-12.0.pre
稳定版本:2.5
参考资料
#文档
相关议题
相关 PR