invariant_ booleans
Learn about the invariant_booleans linter rule.
Conditions should not unconditionally evaluate to
true or to false.
Details
#NOTE: This rule is removed in Dart 3.0.0; it is no longer functional.
DON'T test for conditions that can be inferred at compile time or test the same condition twice.
Conditional statements using a condition which cannot be
anything but false have the effect of making
blocks of code non-functional. If the condition cannot
evaluate to anything but true, the conditional
statement is completely redundant, and makes the code less
readable. It is quite likely that the code does not match the
programmer's intent. Either the condition should be removed or
it should be updated so that it does not always evaluate to
true or false and does not perform
redundant tests. This rule will hint to the test conflicting
with the linted one.
BAD:
// foo can't be both equal and not equal to bar in the same expression
if(foo == bar && something && foo != bar) {...}
BAD:
void compute(int foo) {
if (foo == 4) {
doSomething();
// we know foo is equal to 4 at this point, so the next condition is always false
if (foo > 4) {...}
...
}
...
}
BAD:
void compute(bool foo) {
if (foo) {
return;
}
doSomething();
// foo is always false here
if (foo){...}
...
}
GOOD:
void nestedOK() {
if (foo == bar) {
foo = baz;
if (foo != bar) {...}
}
}
GOOD:
void nestedOk2() {
if (foo == bar) {
return;
}
foo = baz;
if (foo == bar) {...} // OK
}
GOOD:
void nestedOk5() {
if (foo != null) {
if (bar != null) {
return;
}
}
if (bar != null) {...} // OK
}
Enable
#
To enable the invariant_booleans rule, add
invariant_booleans under
linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- invariant_booleans
If you're instead using the YAML map syntax to configure
linter rules, add invariant_booleans: true under
linter > rules:
linter:
rules:
invariant_booleans: true
除非另有说明,文档之所提及适用于 Dart 3.12.2 版本报告页面问题.