引入 package:flutter_lints
概述
#package:flutter_lints
定义了一套推荐的最新代码规范,旨在鼓励 Flutter 应用、包和插件采用良好的编码实践。使用 Flutter 2.5 或更高版本通过 flutter create
创建的项目已默认启用最新推荐的代码规范。在此版本之前创建的项目,可以按照本指南中的说明进行升级。
背景
#在引入 package:flutter_lints
之前,Flutter 框架附带了一套在 analysis_options_user.yaml
中定义的代码规范,如果 Flutter 项目没有定义自定义的 analysis_options.yaml
文件,Dart 分析器就会使用它来识别代码问题。由于 analysis_options_user.yaml
与特定框架版本绑定,因此在不破坏现有应用、包和插件的情况下很难进行演进。因此,analysis_options_user.yaml
中定义的代码规范已经严重过时。为了解决这个问题,创建了 package:flutter_lints
。该包对代码规范集进行版本控制,以便在不破坏现有项目的情况下进行演进。由于该包基于 Dart 的 package:lints
构建,它还将 Flutter 项目推荐的代码规范与 Dart 生态系统的其余部分保持一致。
迁移指南
#请按照以下步骤迁移您的 Flutter 项目,以使用 package:flutter_lints
中最新的推荐代码规范。
通过在项目根目录中运行 flutter pub add --dev flutter_lints
,将 package:flutter_lints
作为开发依赖项添加到您项目的 pubspec.yaml
中。
在项目根目录(与 pubspec.yaml
文件并列)中创建一个 analysis_options.yaml
文件,其内容如下:
include: package:flutter_lints/flutter.yaml
新激活的代码规范集可能会在您的代码中发现一些新问题。要查找这些问题,请在支持 Dart 的 IDE 中打开您的项目,或在命令行运行 flutter analyze
。您可以通过在项目根目录中运行 dart fix --apply
来自动修复一些报告的问题。
现有 custom analysis_options.yaml 文件
#如果您的项目根目录中已有一个自定义的 analysis_options.yaml
文件,请在其顶部添加 include: package:flutter_lints/flutter.yaml
以激活 package:flutter_lints
中的代码规范。如果您的 analysis_options.yaml
已包含一个 include:
指令,您必须决定是保留这些代码规范,还是将其替换为 package:flutter_lints
中的代码规范,因为 Dart 分析器在每个 analysis_options.yaml
文件中只支持一个 include:
指令。
自定义代码规范
#针对给定项目激活的代码规范可以在 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