dart-fix-static-analysis-errors
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseResolving Dart Static Analysis Errors
解决Dart静态分析错误
Contents
目录
Diagnostic Execution
诊断执行
Execute the Dart analyzer to identify static errors, warnings, and informational diagnostics across the codebase.
- Run to evaluate all Dart files in the current directory.
$ dart analyze - Target specific directories or files by appending the path: or
$ dart analyze bin.$ dart analyze lib/main.dart - Enforce strictness by failing on info-level issues using the flag.
--fatal-infos - Apply automated quick-fixes for supported diagnostics using . Preview changes first with
$ dart fix --apply.$ dart fix --dry-run
执行Dart分析器以识别代码库中的静态错误、警告和信息性诊断。
- 运行以评估当前目录下的所有Dart文件。
$ dart analyze - 通过追加路径来指定特定目录或文件:或
$ dart analyze bin。$ dart analyze lib/main.dart - 使用标记,将信息级问题设为致命错误以严格执行检查。
--fatal-infos - 使用为支持的诊断应用自动快速修复。先使用
$ dart fix --apply预览更改。$ dart fix --dry-run
Null Safety & Type Resolution
空安全与类型解析
Address static errors related to Dart's sound null safety and strict type system.
- Nullability: Append to types to explicitly allow
?(e.g.,null).String? - Assertion: Use the postfix bang operator to cast a nullable expression to its underlying non-nullable type when you can guarantee it is not null.
! - Delayed Initialization: Apply the modifier to non-nullable top-level or instance variables that are guaranteed to be initialized before their first read, bypassing the analyzer's definite assignment checks.
late - Named Parameters: Use the modifier for named parameters that do not have a default value and cannot be null.
required - Explicit Downcasts: If static analysis disallows an implicit downcast (e.g., assigning to
List<Animal>), use an explicit cast:List<Cat>.as List<Cat> - Generic Types: Always provide explicit type annotations to generic classes (e.g., ,
List<String>). Avoid using a rawMap<String, dynamic>orListwhich defaults toMap.dynamic
处理与Dart健全空安全和严格类型系统相关的静态错误。
- 可空性: 在类型后添加以显式允许
?(例如null)。String? - 断言: 当你能保证可空表达式不为null时,使用后缀感叹号运算符将其转换为对应的非可空类型。
! - 延迟初始化: 对非可空的顶级变量或实例变量使用修饰符,确保它们在首次读取前完成初始化,从而绕过分析器的确定赋值检查。
late - 命名参数: 对没有默认值且不能为null的命名参数使用修饰符。
required - 显式向下转型: 如果静态分析不允许隐式向下转型(例如将赋值给
List<Animal>),使用显式转型:List<Cat>。as List<Cat> - 泛型类型: 始终为泛型类提供显式类型注解(例如、
List<String>)。避免使用原始的Map<String, dynamic>或List,它们默认会转为Map类型。dynamic
Flow Analysis & Type Promotion
流分析与类型提升
Leverage Dart's control flow analysis to safely promote nullable types to non-nullable types without manual casting.
- Null Checks: Check a local variable against (e.g.,
null) to automatically promote it to a non-nullable type within that block.if (value != null) - Type Tests: Use the operator (e.g.,
is) to promote a variable to a specific subclass or type.if (value is String) - Early Returns: Use early returns, , or
breakto exit a control flow path if a variable is null or the wrong type. The analyzer will promote the variable for the remainder of the scope.throw - Reachability: Use the type for functions that unconditionally throw exceptions or terminate the process. The analyzer uses this to determine unreachable code paths.
Never
利用Dart的控制流分析,无需手动转型即可安全地将可空类型提升为非可空类型。
- Null检查: 检查局部变量是否为(例如
null),分析器会自动在该代码块内将其提升为非可空类型。if (value != null) - 类型测试: 使用运算符(例如
is)将变量提升为特定子类或类型。if (value is String) - 提前返回: 如果变量为null或类型错误,使用提前返回、或
break退出控制流路径。分析器会在剩余作用域中提升该变量的类型。throw - 可达性: 对无条件抛出异常或终止进程的函数使用类型。分析器会利用此类型判断不可达的代码路径。
Never
Analyzer Configuration
分析器配置
Configure the file at the package root to enforce stricter type checks and customize linter rules.
analysis_options.yaml- Enable to prevent implicit downcasts from
strict-casts: true.dynamic - Enable to prevent the analyzer from falling back to
strict-inference: truewhen it cannot infer a type.dynamic - Enable to require explicit type arguments on generic types.
strict-raw-types: true - Suppress specific diagnostics in a file using .
// ignore_for_file: <diagnostic_name> - Suppress a diagnostic on a specific line using .
// ignore: <diagnostic_name>
在包根目录配置文件,以强制执行更严格的类型检查并自定义检查规则。
analysis_options.yaml- 启用以阻止从
strict-casts: true类型进行隐式向下转型。dynamic - 启用以防止分析器在无法推断类型时回退到
strict-inference: true。dynamic - 启用以要求泛型类型提供显式类型参数。
strict-raw-types: true - 使用在文件中禁用特定诊断。
// ignore_for_file: <diagnostic_name> - 使用在特定行禁用诊断。
// ignore: <diagnostic_name>
Workflow: Static Analysis Remediation
工作流程:静态分析修复
Follow this sequential workflow to resolve static analysis errors in a Dart project.
遵循此顺序工作流程解决Dart项目中的静态分析错误。
Task Progress Checklist
任务进度清单
Copy this checklist to track your progress:
- Run to establish a baseline of errors.
$ dart analyze - Run to resolve automatically fixable issues.
$ dart fix --apply - Address remaining Null Safety errors (,
?,!,late).required - Address remaining Type System errors (explicit casts, generic type annotations).
as - Run to verify all errors are resolved.
$ dart analyze - Execute tests or run the application to ensure fixes did not introduce runtime exceptions (e.g., failed casts or uninitialized
asvariables).late
复制此清单跟踪进度:
- 运行建立错误基准。
$ dart analyze - 运行解决可自动修复的问题。
$ dart fix --apply - 处理剩余的空安全错误(、
?、!、late)。required - 处理剩余的类型系统错误(显式转型、泛型类型注解)。
as - 运行验证所有错误已解决。
$ dart analyze - 执行测试或运行应用,确保修复未引入运行时异常(例如失败的转型或未初始化的
as变量)。late
Conditional Logic
条件逻辑
- If working with mixed-version code (legacy Dart 2.9): Disable sound null safety temporarily by passing to
--no-sound-null-safetyordart run, or by addingflutter runto the top of the entrypoint file.// @dart=2.9 - If a field is private and final: Rely on flow analysis for type promotion.
- If a field is public or non-final: Flow analysis cannot promote it. Copy the field to a local variable first, check the local variable for null, and use the local variable.
- 如果处理混合版本代码(旧版Dart 2.9): 通过向或
dart run传递flutter run,或在入口文件顶部添加--no-sound-null-safety,临时禁用健全空安全。// @dart=2.9 - 如果字段是私有且final: 依赖流分析进行类型提升。
- 如果字段是公共或非final: 流分析无法对其进行类型提升。先将字段复制到局部变量,检查局部变量是否为null,然后使用该局部变量。
Feedback Loop
反馈循环
- Run Validator:
$ dart analyze - Review Errors: Identify the file, line number, and diagnostic code.
- Fix: Apply the appropriate null safety or type resolution fix.
- Repeat: Continue until returns "No issues found!".
$ dart analyze
- 运行验证器:
$ dart analyze - 查看错误: 确定文件、行号和诊断代码。
- 修复: 应用适当的空安全或类型解析修复方案。
- 重复: 持续执行直到返回"No issues found!"。
$ dart analyze
Examples
示例
Type Promotion via Local Variable Assignment
通过局部变量赋值实现类型提升
When dealing with nullable instance fields, copy to a local variable to enable flow analysis.
Incorrect (Fails Analysis):
dart
class Coffee {
String? _temperature;
void checkTemp() {
if (_temperature != null) {
// ERROR: Property cannot be promoted because it is not a local variable.
print(_temperature.length);
}
}
}Correct:
dart
class Coffee {
String? _temperature;
void checkTemp() {
final temp = _temperature; // Copy to local variable
if (temp != null) {
// SUCCESS: 'temp' is promoted to non-nullable String.
print(temp.length);
}
}
}处理可空实例字段时,复制到局部变量以启用流分析。
错误示例(分析不通过):
dart
class Coffee {
String? _temperature;
void checkTemp() {
if (_temperature != null) {
// 错误:属性无法被提升,因为它不是局部变量。
print(_temperature.length);
}
}
}正确示例:
dart
class Coffee {
String? _temperature;
void checkTemp() {
final temp = _temperature; // 复制到局部变量
if (temp != null) {
// 成功:'temp'被提升为非可空String类型。
print(temp.length);
}
}
}Strict Analyzer Configuration
严格分析器配置
Implement the following to enforce strict type safety.
analysis_options.yamlyaml
include: package:lints/recommended.yaml
analyzer:
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
errors:
invalid_assignment: error
missing_return: error
dead_code: info实现以下以强制执行严格的类型安全。
analysis_options.yamlyaml
include: package:lints/recommended.yaml
analyzer:
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
errors:
invalid_assignment: error
missing_return: error
dead_code: info