目录

unrelated_type_equality_checks

使用不相关类型的引用调用相等运算符 ==

此规则从 Dart 2.0 开始可用。

规则集:corerecommendedflutter

详情

#

不要比较不相关类型的引用是否相等。

比较彼此都不是子类型的类型的引用很可能返回 false,并且可能无法反映程序员的意图。

来自 package:fixnumInt64Int32 允许与 int 进行比较,前提是 int 位于右侧。lint 允许这种情况作为特殊情况。

错误示例

dart
void someFunction() {
  var x = '1';
  if (x == 1) print('someFunction'); // LINT
}

错误示例

dart
void someFunction1() {
  String x = '1';
  if (x == 1) print('someFunction1'); // LINT
}

错误示例

dart
void someFunction13(DerivedClass2 instance) {
  var other = DerivedClass3();

  if (other == instance) print('someFunction13'); // LINT
}

class ClassBase {}

class DerivedClass1 extends ClassBase {}

abstract class Mixin {}

class DerivedClass2 extends ClassBase with Mixin {}

class DerivedClass3 extends ClassBase implements Mixin {}

正确示例

dart
void someFunction2() {
  var x = '1';
  var y = '2';
  if (x == y) print(someFunction2); // OK
}

正确示例

dart
void someFunction3() {
  for (var i = 0; i < 10; i++) {
    if (i == 0) print(someFunction3); // OK
  }
}

正确示例

dart
void someFunction4() {
  var x = '1';
  if (x == null) print(someFunction4); // OK
}

正确示例

dart
void someFunction7() {
  List someList;

  if (someList.length == 0) print('someFunction7'); // OK
}

正确示例

dart
void someFunction8(ClassBase instance) {
  DerivedClass1 other;

  if (other == instance) print('someFunction8'); // OK
}

正确示例

dart
void someFunction10(unknown) {
  var what = unknown - 1;
  for (var index = 0; index < unknown; index++) {
    if (what == index) print('someFunction10'); // OK
  }
}

正确示例

dart
void someFunction11(Mixin instance) {
  var other = DerivedClass2();

  if (other == instance) print('someFunction11'); // OK
  if (other != instance) print('!someFunction11'); // OK
}

class ClassBase {}

abstract class Mixin {}

class DerivedClass2 extends ClassBase with Mixin {}

用法

#

要启用 unrelated_type_equality_checks 规则,请在 analysis_options.yaml 文件中的 linter > rules 下添加 unrelated_type_equality_checks

analysis_options.yaml
yaml
linter:
  rules:
    - unrelated_type_equality_checks