内容

iterable_contains_unrelated_type

使用不相关类型的引用调用 Iterable<E>.contains

此规则已从最新的 Dart 版本中删除。

详情

#

注意:此规则在 Dart 3.3.0 中已删除;它不再起作用。

**不要** 在 Iterable 上调用 contains,其中实例的类型与参数类型不同。

这样做将调用其元素上的 ==,并且很可能会返回 false

错误

dart
void someFunction() {
  var list = <int>[];
  if (list.contains('1')) print('someFunction'); // LINT
}

错误

dart
void someFunction3() {
  List<int> list = <int>[];
  if (list.contains('1')) print('someFunction3'); // LINT
}

错误

dart
void someFunction8() {
  List<DerivedClass2> list = <DerivedClass2>[];
  DerivedClass3 instance;
  if (list.contains(instance)) print('someFunction8'); // LINT
}

错误

dart
abstract class SomeIterable<E> implements Iterable<E> {}

abstract class MyClass implements SomeIterable<int> {
  bool badMethod(String thing) => this.contains(thing); // LINT
}

正确

dart
void someFunction10() {
  var list = [];
  if (list.contains(1)) print('someFunction10'); // OK
}

正确

dart
void someFunction1() {
  var list = <int>[];
  if (list.contains(1)) print('someFunction1'); // OK
}

正确

dart
void someFunction4() {
  List<int> list = <int>[];
  if (list.contains(1)) print('someFunction4'); // OK
}

正确

dart
void someFunction5() {
  List<ClassBase> list = <ClassBase>[];
  DerivedClass1 instance;
  if (list.contains(instance)) print('someFunction5'); // OK
}

abstract class ClassBase {}

class DerivedClass1 extends ClassBase {}

正确

dart
void someFunction6() {
  List<Mixin> list = <Mixin>[];
  DerivedClass2 instance;
  if (list.contains(instance)) print('someFunction6'); // OK
}

abstract class ClassBase {}

abstract class Mixin {}

class DerivedClass2 extends ClassBase with Mixin {}

正确

dart
void someFunction7() {
  List<Mixin> list = <Mixin>[];
  DerivedClass3 instance;
  if (list.contains(instance)) print('someFunction7'); // OK
}

abstract class ClassBase {}

abstract class Mixin {}

class DerivedClass3 extends ClassBase implements Mixin {}

用法

#

要启用 iterable_contains_unrelated_type 规则,请在您的 analysis_options.yaml 文件中将 iterable_contains_unrelated_type 添加到 **linter > rules** 下

analysis_options.yaml
yaml
linter:
  rules:
    - iterable_contains_unrelated_type