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 映射语法来配置 linter 规则,请在 linter > rules 下添加 omit_local_variable_types: true
analysis_options.yaml
yaml
linter:
rules:
omit_local_variable_types: true
除非另有说明,否则本网站上的文档反映的是 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或 报告问题。