invariant_booleans
条件不应无条件地评估为 true
或 false
。
详情
#NOTE: 此规则在 Dart 3.0.0 中已移除;不再起作用。
DON'T 测试可以在编译时推断出的条件,或两次测试相同的条件。
使用永远为 false
的条件的条件语句会使代码块失效。如果条件永远为 true
,则条件语句完全是多余的,并降低代码的可读性。代码很可能与程序员的意图不符。应该移除条件,或者应该更新条件,使其不会总是评估为 true
或 false
,并且不执行冗余测试。此规则将提示测试与 linted 的规则冲突。
BAD
dart
// foo can't be both equal and not equal to bar in the same expression
if(foo == bar && something && foo != bar) {...}
BAD
dart
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
dart
void compute(bool foo) {
if (foo) {
return;
}
doSomething();
// foo is always false here
if (foo){...}
...
}
GOOD
dart
void nestedOK() {
if (foo == bar) {
foo = baz;
if (foo != bar) {...}
}
}
GOOD
dart
void nestedOk2() {
if (foo == bar) {
return;
}
foo = baz;
if (foo == bar) {...} // OK
}
GOOD
dart
void nestedOk5() {
if (foo != null) {
if (bar != null) {
return;
}
}
if (bar != null) {...} // OK
}
启用
#要启用 invariant_booleans
规则,请在您的 analysis_options.yaml
文件中的 linter > rules 下添加 invariant_booleans
analysis_options.yaml
yaml
linter:
rules:
- invariant_booleans
如果您改为使用 YAML 映射语法配置 linter 规则,请在 linter > rules 下添加 invariant_booleans: true
analysis_options.yaml
yaml
linter:
rules:
invariant_booleans: true
除非另有说明,否则本网站上的文档反映的是 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或报告问题。