omit_obvious_local_variable_types
Omit obvious type annotations for local variables.
This rule is currently experimental and available as of Dart 3.6.
This rule has a quick fix available.
Incompatible rules: always_specify_types
Details
#Don't type annotate initialized local variables when the type is obvious.
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. Hence, local variable type annotations that are obvious should be omitted.
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;
}
const cookbook = <List<Ingredient>>[....];
GOOD:
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>>[....];
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. You may also wish to write a type annotation explicitly because the type of the initializing expression is non-obvious and it will be helpful for future readers of the code to document this type. Or you may wish to commit to a specific type such that future updates of dependencies (in nearby code, in imports, anywhere) will not silently change the type of that variable, thus introducing compile-time errors or run-time bugs in locations where this variable is used. In those cases, go ahead and annotate the variable with the type you want.
GOOD:
Widget build(BuildContext context) {
Widget result = someGenericFunction(42) ?? Text('You won!');
if (applyPadding) {
result = Padding(padding: EdgeInsets.all(8.0), child: result);
}
return result;
}
This rule is experimental. It is being evaluated, and it may be changed or removed. Feedback on its behavior is welcome! The main issue is here: https://github.com/dart-lang/linter/issues/3480.
Usage
#To enable the omit_obvious_local_variable_types
rule, add omit_obvious_local_variable_types
under linter > rules in your analysis_options.yaml
file:
linter:
rules:
- omit_obvious_local_variable_types
Unless stated otherwise, the documentation on this site reflects Dart 3.6.0. Page last updated on 2024-07-03. View source or report an issue.