avoid_init_to_null
Don't explicitly initialize variables to null
.
Details
#From Effective Dart:
DON'T explicitly initialize variables to null
.
If a variable has a non-nullable type or is final
, Dart reports a compile error if you try to use it before it has been definitely initialized. If the variable is nullable and not const
or final
, then it is implicitly initialized to null
for you. There's no concept of "uninitialized memory" in Dart and no need to explicitly initialize a variable to null
to be "safe". Adding = null
is redundant and unneeded.
BAD:
Item? bestDeal(List<Item> cart) {
Item? bestItem = null;
for (final item in cart) {
if (bestItem == null || item.price < bestItem.price) {
bestItem = item;
}
}
return bestItem;
}
GOOD:
Item? bestDeal(List<Item> cart) {
Item? bestItem;
for (final item in cart) {
if (bestItem == null || item.price < bestItem.price) {
bestItem = item;
}
}
return bestItem;
}
Enable
#To enable the avoid_init_to_null
rule, add avoid_init_to_null
under linter > rules in your analysis_options.yaml
file:
linter:
rules:
- avoid_init_to_null
If you're instead using the YAML map syntax to configure linter rules, add avoid_init_to_null: true
under linter > rules:
linter:
rules:
avoid_init_to_null: true
Unless stated otherwise, the documentation on this site reflects Dart 3.7.0. Page last updated on 2025-01-27. View source or report an issue.