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>>[....];有時推斷出的型別並非你希望變數擁有的型別。例如,你可能打算稍後賦值其他型別的值。你也可能希望顯式地編寫型別註解,因為初始化表示式的型別不明顯,而且這有助於未來的程式碼讀者理解該型別。或者你可能希望固定為一個特定型別,這樣將來依賴項的更新(在附近程式碼、匯入或其他任何地方)就不會悄無聲息地改變該變數的型別,從而在使用該變數的位置引入編譯時錯誤或執行時 bug。在這些情況下,儘管使用你想要的型別來註解變數。
正例
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