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