dart-static-analysis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDart Static Analysis and Type Promotion
Dart静态分析与类型提升
Goal
目标
Configures Dart static analysis environments, enforces strict type checking, and resolves complex type promotion failures. Assumes a standard Dart or Flutter project structure with access to the Dart SDK CLI and a file at the project root.
pubspec.yaml配置Dart静态分析环境,强制执行严格类型检查,并解决复杂的类型提升失败问题。假设项目为标准Dart或Flutter项目结构,可访问Dart SDK CLI,且项目根目录存在pubspec.yaml文件。
Instructions
操作步骤
-
Determine Project Environment STOP AND ASK THE USER: "Is this a pure Dart project or a Flutter project? Are there any specific linter rules you want to explicitly disable?"
-
Configure Dependencies Based on the user's response, add the appropriate linting package as a development dependency. For pure Dart:bash
dart pub add --dev lintsFor Flutter:bashflutter pub add --dev flutter_lints -
ConfigureCreate or update the
analysis_options.yamlfile at the project root. You MUST enforce strict language modes and include the recommended lint rules.analysis_options.yamlyamlinclude: package:lints/recommended.yaml # Use package:flutter_lints/recommended.yaml for Flutter analyzer: language: strict-casts: true strict-inference: true strict-raw-types: true exclude: - "**/*.g.dart" - "**/*.freezed.dart" linter: rules: # Add specific rule overrides here if requested by the user # e.g., avoid_print: false -
Decision Logic: Resolving Type Promotion Failures When encountering type promotion failures during analysis, apply the following decision logic to refactor the code:
-
Scenario A: Promoting an instance field, getter, or
this- Reason: The analyzer cannot guarantee that fields, getters, or will return a stable value.
this - Fix: Assign the property to a local variable before performing the null or type check.
final
dart// DO NOT DO THIS: // if (_myNullableField != null) { print(_myNullableField.isEven); } // DO THIS: final myField = _myNullableField; if (myField != null) { print(myField.isEven); } - Reason: The analyzer cannot guarantee that fields, getters, or
-
Scenario B: Variable is write-captured by a closure or local function
- Reason: The analyzer assumes the closure could execute at any time, invalidating the promotion.
- Fix: Shadow the variable locally before the closure or before the check.
dart// DO THIS: final localValue = capturedValue; if (localValue != null) { print(localValue.isEven); } -
Scenario C: Subtype mismatch during promotion
- Reason: Promoting to a type that is not a subtype of the current promoted type.
- Fix: Use a redundant type check () or check against a more precise subtype.
as
dartif (o is Comparable) { if (o is String) { // String is a subtype of Comparable print(o.matchAsPrefix('foo')); } }
-
-
Apply Automated Fixes Execute the Dart fix command to bulk-apply safe, automated fixes for common lint and migration issues.bash
dart fix --apply -
Validate and Fix Run the static analyzer to catch potential bugs and style violations early.bash
dart analyzeIfreturns errors or warnings, iteratively apply the decision logic in Step 4 to resolve them. Do not proceed until the analysis returns zero issues.dart analyze
-
确定项目环境 请暂停并询问用户:“这是纯Dart项目还是Flutter项目?您是否需要显式禁用某些特定的Linter规则?”
-
配置依赖 根据用户的回复,添加对应的 lint 包作为开发依赖。 纯Dart项目:bash
dart pub add --dev lintsFlutter项目:bashflutter pub add --dev flutter_lints -
配置analysis_options.yaml 在项目根目录创建或更新analysis_options.yaml文件。必须启用严格语言模式并包含推荐的Lint规则。yaml
include: package:lints/recommended.yaml # Flutter项目请使用package:flutter_lints/recommended.yaml analyzer: language: strict-casts: true strict-inference: true strict-raw-types: true exclude: - "**/*.g.dart" - "**/*.freezed.dart" linter: rules: # 若用户有要求,在此添加特定规则覆盖 # 例如:avoid_print: false -
决策逻辑:解决类型提升失败问题 当分析过程中遇到类型提升失败时,应用以下决策逻辑重构代码:
-
场景A:提升实例字段、getter或this
- 原因:分析器无法保证字段、getter或this会返回稳定的值。
- 修复方案:在执行空值或类型检查前,将属性赋值给一个本地final变量。
dart// 错误示例: // if (_myNullableField != null) { print(_myNullableField.isEven); } // 正确示例: final myField = _myNullableField; if (myField != null) { print(myField.isEven); } -
场景B:变量被闭包或本地函数捕获写入
- 原因:分析器认为闭包可能在任意时间执行,导致提升失效。
- 修复方案:在闭包或检查前,在本地遮蔽该变量。
dart// 正确示例: final localValue = capturedValue; if (localValue != null) { print(localValue.isEven); } -
场景C:提升时出现子类型不匹配
- 原因:提升的类型并非当前提升类型的子类型。
- 修复方案:使用冗余类型检查(as)或针对更精确的子类型进行检查。
dartif (o is Comparable) { if (o is String) { // String是Comparable的子类型 print(o.matchAsPrefix('foo')); } }
-
-
应用自动修复 执行Dart修复命令,批量应用安全的自动修复,解决常见的Lint和迁移问题。bash
dart fix --apply -
验证与修复 运行静态分析器,尽早发现潜在的bug和风格违规问题。bash
dart analyze如果返回错误或警告,重复应用步骤4中的决策逻辑来解决问题。直到分析返回零问题后再继续。dart analyze
Constraints
约束条件
- DO run to catch potential bugs and style violations early.
dart analyze - DO configure custom lint rules in (prefer using
analysis_options.yamlorpackage:lints).package:flutter_lints - DO resolve "non-promotion" reasons by using local variables for field promotion.
- DO use for bulk-fixing common lint and migration issues.
dart fix --apply - AVOID ignoring lints manually (e.g., or
// ignore: ...) unless absolutely necessary; prefer fixing the root cause.// ignore_for_file: ... - NEVER use the deprecated under
implicit-casts: false; always usestrong-modeunderstrict-casts: true.language - Related Skills: ,
dart-effective-style.dart-api-design
- 务必运行以尽早发现潜在的bug和风格违规问题。
dart analyze - 务必在analysis_options.yaml中配置自定义Lint规则(优先使用package:lints或package:flutter_lints)。
- 务必通过使用本地变量处理字段提升来解决“无法提升”的问题。
- 务必使用批量修复常见的Lint和迁移问题。
dart fix --apply - 除非绝对必要,否则避免手动忽略Lint(例如或
// ignore: ...);优先修复根本原因。// ignore_for_file: ... - 切勿在strong-mode下使用已弃用的;务必在language下使用
implicit-casts: false。strict-casts: true - 相关技能:、
dart-effective-style。dart-api-design