dart-static-analysis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dart 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
pubspec.yaml
file at the project root.
配置Dart静态分析环境,强制执行严格类型检查,并解决复杂的类型提升失败问题。假设项目为标准Dart或Flutter项目结构,可访问Dart SDK CLI,且项目根目录存在pubspec.yaml文件。

Instructions

操作步骤

  1. 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?"
  2. 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 lints
    For Flutter:
    bash
    flutter pub add --dev flutter_lints
  3. Configure
    analysis_options.yaml
    Create or update the
    analysis_options.yaml
    file at the project root. You MUST enforce strict language modes and include the recommended lint rules.
    yaml
    include: 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
  4. 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
        this
        will return a stable value.
      • Fix: Assign the property to a local
        final
        variable before performing the null or type check.
      dart
      // DO NOT DO THIS:
      // if (_myNullableField != null) { print(_myNullableField.isEven); }
      
      // DO THIS:
      final myField = _myNullableField;
      if (myField != null) {
        print(myField.isEven);
      }
    • 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 (
        as
        ) or check against a more precise subtype.
      dart
      if (o is Comparable) {
        if (o is String) { // String is a subtype of Comparable
          print(o.matchAsPrefix('foo'));
        }
      }
  5. Apply Automated Fixes Execute the Dart fix command to bulk-apply safe, automated fixes for common lint and migration issues.
    bash
    dart fix --apply
  6. Validate and Fix Run the static analyzer to catch potential bugs and style violations early.
    bash
    dart analyze
    If
    dart analyze
    returns errors or warnings, iteratively apply the decision logic in Step 4 to resolve them. Do not proceed until the analysis returns zero issues.
  1. 确定项目环境 请暂停并询问用户:“这是纯Dart项目还是Flutter项目?您是否需要显式禁用某些特定的Linter规则?”
  2. 配置依赖 根据用户的回复,添加对应的 lint 包作为开发依赖。 纯Dart项目:
    bash
    dart pub add --dev lints
    Flutter项目:
    bash
    flutter pub add --dev flutter_lints
  3. 配置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
  4. 决策逻辑:解决类型提升失败问题 当分析过程中遇到类型提升失败时,应用以下决策逻辑重构代码:
    • 场景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)或针对更精确的子类型进行检查。
      dart
      if (o is Comparable) {
        if (o is String) { // String是Comparable的子类型
          print(o.matchAsPrefix('foo'));
        }
      }
  5. 应用自动修复 执行Dart修复命令,批量应用安全的自动修复,解决常见的Lint和迁移问题。
    bash
    dart fix --apply
  6. 验证与修复 运行静态分析器,尽早发现潜在的bug和风格违规问题。
    bash
    dart analyze
    如果
    dart analyze
    返回错误或警告,重复应用步骤4中的决策逻辑来解决问题。直到分析返回零问题后再继续。

Constraints

约束条件

  • DO run
    dart analyze
    to catch potential bugs and style violations early.
  • DO configure custom lint rules in
    analysis_options.yaml
    (prefer using
    package:lints
    or
    package:flutter_lints
    ).
  • DO resolve "non-promotion" reasons by using local variables for field promotion.
  • DO use
    dart fix --apply
    for bulk-fixing common lint and migration issues.
  • AVOID ignoring lints manually (e.g.,
    // ignore: ...
    or
    // ignore_for_file: ...
    ) unless absolutely necessary; prefer fixing the root cause.
  • NEVER use the deprecated
    implicit-casts: false
    under
    strong-mode
    ; always use
    strict-casts: true
    under
    language
    .
  • Related Skills:
    dart-effective-style
    ,
    dart-api-design
    .
  • 务必运行
    dart analyze
    以尽早发现潜在的bug和风格违规问题。
  • 务必在analysis_options.yaml中配置自定义Lint规则(优先使用package:lints或package:flutter_lints)。
  • 务必通过使用本地变量处理字段提升来解决“无法提升”的问题。
  • 务必使用
    dart fix --apply
    批量修复常见的Lint和迁移问题。
  • 除非绝对必要,否则避免手动忽略Lint(例如
    // ignore: ...
    // ignore_for_file: ...
    );优先修复根本原因。
  • 切勿在strong-mode下使用已弃用的
    implicit-casts: false
    ;务必在language下使用
    strict-casts: true
  • 相关技能:
    dart-effective-style
    dart-api-design