目录

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 文件中的 linter > rules 下添加 iterable_contains_unrelated_type

analysis_options.yaml
yaml
linter:
  rules:
    - iterable_contains_unrelated_type