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 對應語法來設定 linter 規則,請在 linter > rules 下新增 omit_local_variable_types: true
analysis_options.yaml
yaml
linter:
rules:
omit_local_variable_types: true
除非另有說明,否則本網站上的文件反映 Dart 3.7.1 版本。頁面最後更新於 2025-03-07。檢視原始碼 或 回報問題。