omit_local_variable_types
Omit type annotations for local variables.
此规则自 Dart 2.0 版本起可用。
此规则提供 快速修复 。
_不兼容规则:always_specify_types , specify_nonobvious_local_variable_types _
详情
#DON'T redundantly type annotate initialized local variables.
Local variables, especially in modern code where functions tend to be small, have very little scope. Omitting the type focuses the reader's attention on the more important name of the variable and its initialized value.
BAD:
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;
}
GOOD:
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;
}
Sometimes the inferred type is not the type you want the variable to have. For example, you may intend to assign values of other types later. In that case, annotate the variable with the type you want.
GOOD:
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
规则,请在你的 analysis_options.yaml
文件中,在 linter > rules 下添加 omit_local_variable_types
:
linter:
rules:
- omit_local_variable_types
除非另有说明,否则本网站上的文档反映的是 Dart 3.6.0。页面最后更新于 2025-02-05。 查看源代码 或 报告问题.