specify_ nonobvious_ local_ variable_ types
Learn about the specify_nonobvious_local_variable_types linter rule.
Specify non-obvious type annotations for local variables.
Details
#Do type annotate initialized local variables when the type is non-obvious.
Type annotations on local variables can serve as a request for type inference, documenting the expected outcome of the type inference step, and declaratively allowing the compiler and analyzer to solve the possibly complex task of finding type arguments and annotations in the initializing expression that yield the desired result.
Type annotations on local variables can also inform readers about the type of the initializing expression, which will allow them to proceed reading the subsequent lines of code with known good information about the type of the given variable (which may not be immediately evident by looking at the initializing expression).
BAD:
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
var desserts = genericFunctionDeclaredFarAway(<num>[42], 'Something');
for (final recipe in cookbook) {
if (pantry.containsAll(recipe)) {
desserts.add(recipe);
}
}
return desserts;
}
const List<List<Ingredient>> cookbook = ...;
GOOD:
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
List<List<Ingredient>> desserts = genericFunctionDeclaredFarAway(
<num>[42],
'Something',
);
for (final List<Ingredient> recipe in cookbook) {
if (pantry.containsAll(recipe)) {
desserts.add(recipe);
}
}
return desserts;
}
const List<List<Ingredient>> cookbook = ...;
This rule is experimental. It is being evaluated, and it might be changed or removed. Feedback on its behavior is welcome! The primary relevant issue is dart-lang/sdk#58773.
Incompatible rules
#
The specify_nonobvious_local_variable_types lint is incompatible with the following rules:
Enable
#
To enable the specify_nonobvious_local_variable_types rule, add specify_nonobvious_local_variable_types
under
linter > rules in your analysis_options.yaml
file:
linter:
rules:
- specify_nonobvious_local_variable_types
If you're instead using the YAML map syntax to configure linter rules,
add specify_nonobvious_local_variable_types: true under linter > rules:
linter:
rules:
specify_nonobvious_local_variable_types: true
Unless stated otherwise, the documentation on this site reflects Dart 3.10.3. Report an issue.