omit_obvious_local_variable_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/sdk/issues/58773。
不兼容的规则
#`omit_obvious_local_variable_types` 规则与以下规则不兼容
启用
#要启用 `omit_obvious_local_variable_types` 规则,请在您的 analysis_options.yaml
文件中的 **linter > rules** 下添加 `omit_obvious_local_variable_types`。
linter:
rules:
- omit_obvious_local_variable_types
如果您改为使用 YAML 映射语法来配置 linter 规则,请在 **linter > rules** 下添加 `omit_obvious_local_variable_types: true`。
linter:
rules:
omit_obvious_local_variable_types: true
除非另有说明,否则本网站上的文档反映了 Dart 3.7.1 版本。页面上次更新于 2025-03-07。查看源代码 或 报告问题。