跳到主要內容

omit_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;
}

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

  return desserts;
}

有時推斷出的型別並非你希望該變數擁有的型別。例如,你可能打算之後分配其他型別的值。在這種情況下,請使用你期望的型別來註解該變數。

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

不相容規則

#

omit_local_variable_types 規則與以下規則不相容

啟用

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - omit_local_variable_types

如果你正在使用 YAML map 語法來配置 Linter 規則,請在 linter > rules 下新增 omit_local_variable_types: true

analysis_options.yaml
yaml
linter:
  rules:
    omit_local_variable_types: true