omit_local_variable_types
省略區域變數的類型註釋。
此規則從 Dart 2.0 開始可用。
此規則有可用的快速修正。
不相容的規則:always_specify_types、specify_nonobvious_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
規則,請在您的 analysis_options.yaml
檔案的 linter > rules 下方加入 omit_local_variable_types
。
analysis_options.yaml
yaml
linter:
rules:
- omit_local_variable_types
除非另有說明,否則本網站上的文件反映的是 Dart 3.6.0。頁面最後更新於 2024-07-03。 檢視原始碼或回報問題。