omit_obvious_local_variable_types
省略區域變數的明顯類型註解。
此規則目前為實驗性,並於 Dart 3.6 開始提供。
此規則有可用的快速修正。
不相容規則:always_specify_types
詳細資料
#當類型很明顯時,不要為已初始化的區域變數加上類型註解。
區域變數,尤其是在現代程式碼中,函式往往很小,範圍很小。省略類型會將讀者的注意力集中在更重要的變數名稱及其初始化值。因此,應該省略明顯的區域變數類型註解。
不良範例
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>>[....];
良好範例
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>>[....];
有時推斷的類型並非您希望變數擁有的類型。例如,您可能打算稍後指派其他類型的值。您也可能希望明確撰寫類型註解,因為初始化運算式的類型不明顯,並且這對於未來程式碼的讀者記錄此類型很有幫助。或者,您可能希望提交特定類型,以便未來更新相依性(在附近的程式碼中、在匯入中、任何地方)不會靜默地變更該變數的類型,從而在使用此變數的位置引入編譯時期錯誤或執行時期錯誤。在這些情況下,請繼續使用您想要的類型註解變數。
良好範例
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/linter/issues/3480。
用法
#若要啟用 omit_obvious_local_variable_types
規則,請在 analysis_options.yaml
檔案中的 linter > rules 下方新增 omit_obvious_local_variable_types
linter:
rules:
- omit_obvious_local_variable_types
除非另有說明,否則本網站的文件反映的是 Dart 3.6.0。頁面最後更新時間為 2024-07-03。 檢視原始碼 或 回報問題。