跳到主要內容

omit_obvious_local_variable_types

實驗性
提供修復

省略區域變數中顯而易見的類型註解。

詳細資訊

#

當類型顯而易見時,請勿為初始化的區域變數添加類型註解。

區域變數,尤其是在現代程式碼中,函式往往很小,作用域也很小。省略類型可將讀者的注意力集中在變數更重要的名稱及其初始值上。因此,應該省略顯而易見的區域變數類型註解。

不良

dart
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
  List<List<Ingredient>> desserts = <List<Ingredient>>[];
  for (final List<Ingredient> recipe in cookbook) {
    if (pantry.containsAll(recipe)) {
      desserts.add(recipe);
    }
  }

  return desserts;
}

const cookbook = <List<Ingredient>>[....];

良好

dart
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
  var desserts = <List<Ingredient>>[];
  for (final List<Ingredient> recipe in cookbook) {
    if (pantry.containsAll(recipe)) {
      desserts.add(recipe);
    }
  }

  return desserts;
}

const cookbook = <List<Ingredient>>[....];

有時推斷的類型並非您希望變數擁有的類型。例如,您可能打算稍後分配其他類型的值。您可能也希望明確地編寫類型註解,因為初始化表達式的類型不明顯,並且記錄此類型將對程式碼的未來讀者有所幫助。或者,您可能希望提交到特定類型,以便將來更新依賴項(在附近的程式碼、匯入中、任何地方)不會靜默地更改該變數的類型,從而在使用此變數的位置引入編譯時錯誤或執行時錯誤。在這些情況下,請繼續使用您想要的類型註解變數。

良好

dart
Widget build(BuildContext context) {
  Widget result = someGenericFunction(42) ?? Text('You won!');
  if (applyPadding) {
    result = Padding(padding: EdgeInsets.all(8.0), child: result);
  }
  return result;
}

此規則為實驗性。 它正在評估中,並且可能會被更改或移除。歡迎對其行為提供反饋!主要問題在這裡:https://github.com/dart-lang/sdk/issues/58773。

不相容的規則

#

omit_obvious_local_variable_types 規則與以下規則不相容

啟用

#

若要啟用 omit_obvious_local_variable_types 規則,請在您的 analysis_options.yaml 檔案中的 linter > rules 下新增 omit_obvious_local_variable_types

analysis_options.yaml
yaml
linter:
  rules:
    - omit_obvious_local_variable_types

如果您改用 YAML 地圖語法來配置 linter 規則,請在 linter > rules 下新增 omit_obvious_local_variable_types: true

analysis_options.yaml
yaml
linter:
  rules:
    omit_obvious_local_variable_types: true