unnecessary_null_comparison
The operand can't be 'null', so the condition is always 'false'.
The operand can't be 'null', so the condition is always 'true'.
The operand must be 'null', so the condition is always 'false'.
The operand must be 'null', so the condition is always 'true'.
Description
#The analyzer produces this diagnostic when it finds an equality comparison
(either ==
or !=
) with one operand of null
and the other operand
can't be null
. Such comparisons are always either true
or false
, so
they serve no purpose.
Examples
#The following code produces this diagnostic because x
can never be
null
, so the comparison always evaluates to true
:
void f(int x) {
if (x != null) {
print(x);
}
}
The following code produces this diagnostic because x
can never be
null
, so the comparison always evaluates to false
:
void f(int x) {
if (x == null) {
throw ArgumentError("x can't be null");
}
}
Common fixes
#If the other operand should be able to be null
, then change the type of
the operand:
void f(int? x) {
if (x != null) {
print(x);
}
}
If the other operand really can't be null
, then remove the condition:
void f(int x) {
print(x);
}
除非另有说明,文档之所提及适用于 Dart 3.7.3 版本,本页面最后更新时间: 2025-05-08。 查看文档源码 或者 报告页面问题。