Dart-仅当null(??=)给出警告消息时才赋值



当我执行这个小飞镖程序时:

void main() {
int? someint;
someint ??= 123;
someint ??= 246;
print(someint);
}

我收到以下警告信息;

$ dart test.dart 
test.dart:4:3: Warning: Operand of null-aware operation '??=' has type 'int' which excludes null.
someint ??= 246;
^
123

因此,一切都如预期的那样工作,但警告消息令人讨厌。有什么方法可以抑制此警告消息吗?

这只是一个警告,因为编译器知道赋值不可能发生,因为您之前刚刚进行了零赋值。飞镖垫上有一条更好的错误消息:

void main() {
int? someint;
someint ??= 123;
someint ??= 246; // <- warning here
print(someint);
}
line 4 • The left operand can't be null, so the right operand is never executed. (view docs)
Try removing the operator and the right operand.

您的代码仍然可以编译,尽管没有理由再进行一次零赋值,因为它永远不会运行。

最新更新