avoid_init_to_null
Don't explicitly initialize variables to null.
此规则自 Dart 2.0 版本起可用。
_规则集:recommended , flutter _
此规则提供 快速修复 。
详情
#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;
}使用方法
#要启用 avoid_init_to_null 规则,请在你的 analysis_options.yaml 文件中,在 linter > rules 下添加 avoid_init_to_null :
linter:
rules:
- avoid_init_to_null除非另有说明,否则本网站上的文档反映的是 Dart 3.6.0。页面最后更新于 2025-02-05。 查看源代码 或 报告问题.