avoid_ double_ and_ int_ checks
Details about the 'avoid_double_and_int_checks' diagnostic produced by the Dart analyzer.
Explicit check for double or int.
Description
#
The analyzer produces this diagnostic when an
if statement tests the type of a variable with
is double and the following
else if tests the same variable with
is int.
When compiled to JavaScript, both int and
double values are represented as JavaScript
Number values. Because every
int value also satisfies the
is double check, the is int branch
is unreachable.
To learn more about how Dart represents numbers on different platforms, including when compiled to JavaScript, check out Numbers in Dart.
Example
#
The following code produces this diagnostic because
x is type tested with is double and
then is int, which makes the
is int branch unreachable when compiled to
JavaScript:
void f(Object x) {
if (x is double) {
print('double');
} else if (x is int) {
print('int');
}
}
Common fixes
#
If the distinction between int and
double isn't meaningful, then check if the type
is num instead:
void f(Object x) {
if (x is num) {
print('num');
}
}
If both branches are needed and it's ok for integer
double values (such as 3.0) to take
the is int branch, then check
is int first. This ensures that integer values
take the is int branch on all platforms:
void f(Object x) {
if (x is int) {
print('int');
} else if (x is double) {
print('double');
}
}
除非另有说明,文档之所提及适用于 Dart 3.12.2 版本报告页面问题.