dart-run-static-analysis

dart-run-static-analysis

熱門

執行 `dart analyze` 來識別警告和錯誤,並使用 `dart fix --apply` 自動解決機械性的 lint 問題。在開發過程中用於確保程式碼品質,並在提交變更前使用。

392星標
25分支
更新於 2026/7/10
SKILL.md
readonlyread-only
name
dart-run-static-analysis
description

執行 `dart analyze` 來識別警告和錯誤,並使用 `dart fix --apply` 自動解決機械性的 lint 問題。在開發過程中用於確保程式碼品質,並在提交變更前使用。

分析與修正 Dart 程式碼

目錄

分析設定

使用位於套件根目錄的 analysis_options.yaml 檔案來設定 Dart 分析器。

  • 基礎設定: 務必使用 include: 指令包含標準規則集(例如 package:lints/recommended.yamlpackage:flutter_lints/flutter.yaml)。
  • 嚴格型別檢查:analyzer: language: 節點下啟用嚴格型別檢查,以防止隱式向下轉型和動態推斷。設定 strict-casts: truestrict-inference: truestrict-raw-types: true
  • Linter 規則:linter: rules: 節點下明確啟用或停用特定規則。當覆寫已包含的規則時,使用鍵值對應(rule_name: true/false);當定義全新的規則集時,使用列表(- rule_name)。請勿在同一個 rules 區塊中混合使用列表和對應語法。
  • 格式化設定:formatter: 節點下設定 dart format 的行為。設定 page_width(預設為 80)和 trailing_commasautomatepreserve)。
  • 分析器外掛:analyzer: plugins: 節點下新增外掛來啟用自訂診斷。請確保外掛套件已作為 dev_dependency 新增至 pubspec.yaml

診斷抑制

當診斷(lint 或警告)產生誤判或適用於產生的程式碼時,請明確抑制它。

  • 檔案層級排除:analysis_options.yaml 中使用 analyzer: exclude: 節點,透過 glob 模式排除整個檔案或目錄(例如 **/*.g.dart)。
  • 檔案層級抑制: 在 Dart 檔案頂端新增 // ignore_for_file: <diagnostic_code>,以抑制整個檔案的特定診斷。使用 // ignore_for_file: type=lint 來抑制所有 linter 規則。
  • 行層級抑制: 在違規程式碼的上一行新增 // ignore: <diagnostic_code>,或附加在違規行的結尾。
  • Pubspec 抑制:pubspec.yaml 檔案中,於違規行的上方新增 # ignore: <diagnostic_code>(例如 # ignore: sort_pub_dependencies)。
  • 外掛診斷: 在抑制外掛特定的問題時,請在外掛名稱前加上診斷碼(例如 // ignore: some_plugin/some_code)。

工作流程:執行靜態分析

使用此工作流程來識別型別相關的錯誤、風格違規和潛在的執行時期錯誤。

任務進度:

  • [ ] 1. 確認專案根目錄中存在 analysis_options.yaml
  • [ ] 2. 使用 analyze_files MCP 工具(如果可用)或 CLI 指令 dart analyze <target_directory> 來執行分析器。
  • [ ] 3. 檢閱診斷輸出。
  • [ ] 4. 如果資訊層級的問題必須視為失敗,請附加 --fatal-infos 旗標。
  • [ ] 5. 手動解決回報的錯誤,或繼續進行自動修正工作流程。

工作流程:套用自動修正

使用此工作流程來解決過時的 API 使用方式、套用快速修正,以及遷移程式碼(例如 Dart 3 遷移)。

任務進度:

  • [ ] 1. 使用 dart_fix MCP 工具或 CLI 指令 dart fix --dry-run 執行試執行,以預覽建議的變更。
  • [ ] 2. 檢閱建議的修正,確保它們符合預期的架構。
  • [ ] 3. 如果需要其他修正,請確認 analysis_options.yaml 中已啟用對應的 linter 規則。
  • [ ] 4. 使用 dart_fix MCP 工具或 CLI 指令 dart fix --apply 套用修正。
  • [ ] 5. 使用 dart_format MCP 工具或 CLI 指令 dart format . 格式化修改後的程式碼。
  • [ ] 6. 執行靜態分析工作流程,以確認所有診斷都已解決。

範例

完整的 analysis_options.yaml

include: package:flutter_lints/recommended.yaml

analyzer:
  exclude:
    - "**/*.g.dart"
    - "lib/generated/**"
  language:
    strict-casts: true
    strict-inference: true
    strict-raw-types: true
  errors:
    todo: ignore
    invalid_assignment: warning
    missing_return: error

linter:
  rules:
    avoid_shadowing_type_parameters: false
    await_only_futures: true
    use_super_parameters: true

formatter:
  page_width: 100
  trailing_commas: preserve

行內診斷抑制

// 抑制整個檔案
// ignore_for_file: unused_local_variable, dead_code

void processData() {
  // 抑制特定行
  // ignore: invalid_assignment
  int x = '';
  
  const y = 10; // ignore: constant_identifier_names
}