跳到主要內容

switch_on_type

穩定

避免對 'Type' 使用 switch 語句。

詳情

#

避免Type 使用 switch。

Type 使用 switch 不具備型別安全性,並且在類層次結構發生變化時可能導致 bug。建議改為對變數使用模式匹配。

錯誤示例

dart
void f(Object o) {
  switch (o.runtimeType) {
    case int:
      print('int');
    case String:
      print('String');
  }
}

正確示例

dart
void f(Object o) {
  switch(o) {
    case int():
      print('int');
    case String _:
      print('String');
    default:
      print('other');
  }
}

啟用

#

要啟用 switch_on_type 規則,請將 switch_on_type 新增到你的 analysis_options.yaml 檔案中 linter > rules 下方

analysis_options.yaml
yaml
linter:
  rules:
    - switch_on_type

如果你使用 YAML 對映語法配置 linter 規則,請在 linter > rules 下方新增 switch_on_type: true

analysis_options.yaml
yaml
linter:
  rules:
    switch_on_type: true