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
除非另有说明,文档之所提及适用于 Dart 3.7.0 版本,本页面最后更新时间: 2025-01-27。 查看文档源码 或者 报告页面问题。