dart-fix-static-analysis-errors

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Resolving Dart Static Analysis Errors

解决Dart静态分析错误

Contents

目录

Diagnostic Execution

诊断执行

Execute the Dart analyzer to identify static errors, warnings, and informational diagnostics across the codebase.
  • Run
    $ dart analyze
    to evaluate all Dart files in the current directory.
  • Target specific directories or files by appending the path:
    $ dart analyze bin
    or
    $ dart analyze lib/main.dart
    .
  • Enforce strictness by failing on info-level issues using the
    --fatal-infos
    flag.
  • Apply automated quick-fixes for supported diagnostics using
    $ dart fix --apply
    . Preview changes first with
    $ dart fix --dry-run
    .
执行Dart分析器以识别代码库中的静态错误、警告和信息性诊断。
  • 运行
    $ dart analyze
    以评估当前目录下的所有Dart文件。
  • 通过追加路径来指定特定目录或文件:
    $ 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
    null
    (e.g.,
    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
    late
    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.
  • Named Parameters: Use the
    required
    modifier for named parameters that do not have a default value and cannot be null.
  • Explicit Downcasts: If static analysis disallows an implicit downcast (e.g., assigning
    List<Animal>
    to
    List<Cat>
    ), use an explicit cast:
    as List<Cat>
    .
  • Generic Types: Always provide explicit type annotations to generic classes (e.g.,
    List<String>
    ,
    Map<String, dynamic>
    ). Avoid using a raw
    List
    or
    Map
    which defaults to
    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
    null
    (e.g.,
    if (value != null)
    ) to automatically promote it to a non-nullable type within that block.
  • Type Tests: Use the
    is
    operator (e.g.,
    if (value is String)
    ) to promote a variable to a specific subclass or type.
  • Early Returns: Use early returns,
    break
    , or
    throw
    to 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.
  • Reachability: Use the
    Never
    type for functions that unconditionally throw exceptions or terminate the process. The analyzer uses this to determine unreachable code paths.
利用Dart的控制流分析,无需手动转型即可安全地将可空类型提升为非可空类型。
  • Null检查: 检查局部变量是否为
    null
    (例如
    if (value != null)
    ),分析器会自动在该代码块内将其提升为非可空类型。
  • 类型测试: 使用
    is
    运算符(例如
    if (value is String)
    )将变量提升为特定子类或类型。
  • 提前返回: 如果变量为null或类型错误,使用提前返回、
    break
    throw
    退出控制流路径。分析器会在剩余作用域中提升该变量的类型。
  • 可达性: 对无条件抛出异常或终止进程的函数使用
    Never
    类型。分析器会利用此类型判断不可达的代码路径。

Analyzer Configuration

分析器配置

Configure the
analysis_options.yaml
file at the package root to enforce stricter type checks and customize linter rules.
  • Enable
    strict-casts: true
    to prevent implicit downcasts from
    dynamic
    .
  • Enable
    strict-inference: true
    to prevent the analyzer from falling back to
    dynamic
    when it cannot infer a type.
  • Enable
    strict-raw-types: true
    to require explicit type arguments on generic types.
  • 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
    $ dart analyze
    to establish a baseline of errors.
  • Run
    $ dart fix --apply
    to resolve automatically fixable issues.
  • Address remaining Null Safety errors (
    ?
    ,
    !
    ,
    late
    ,
    required
    ).
  • Address remaining Type System errors (explicit
    as
    casts, generic type annotations).
  • Run
    $ dart analyze
    to verify all errors are resolved.
  • Execute tests or run the application to ensure fixes did not introduce runtime exceptions (e.g., failed
    as
    casts or uninitialized
    late
    variables).
复制此清单跟踪进度:
  • 运行
    $ 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
    --no-sound-null-safety
    to
    dart run
    or
    flutter run
    , or by adding
    // @dart=2.9
    to the top of the entrypoint file.
  • 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

反馈循环

  1. Run Validator:
    $ dart analyze
  2. Review Errors: Identify the file, line number, and diagnostic code.
  3. Fix: Apply the appropriate null safety or type resolution fix.
  4. Repeat: Continue until
    $ dart analyze
    returns "No issues found!".
  1. 运行验证器:
    $ dart analyze
  2. 查看错误: 确定文件、行号和诊断代码。
  3. 修复: 应用适当的空安全或类型解析修复方案。
  4. 重复: 持续执行直到
    $ dart analyze
    返回"No issues found!"。

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
analysis_options.yaml
to enforce strict type safety.
yaml
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.yaml
以强制执行严格的类型安全。
yaml
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