avoid_init_to_null
Don't explicitly initialize variables to null
.
This rule is available as of Dart 2.0.
Rule sets: recommended, flutter
This rule has a quick fix available.
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;
}
Usage
#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
除非另有说明,文档之所提及适用于 Dart 3.5.4 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。