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