跳到主要内容

collection_methods_unrelated_type

稳定
核心

使用不相关类型的参数调用各种集合方法。

详情

#

不要使用不相关类型的参数调用某些集合方法。

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

传递给集合方法的参数应按如下方式与集合类型相关:

  • Iterable<E>.contains 的参数应与 E 相关
  • List<E>.remove 的参数应与 E 相关
  • Map<K, V>.containsKey 的参数应与 K 相关
  • Map<K, V>.containsValue 的参数应与 V 相关
  • Map<K, V>.remove 的参数应与 K 相关
  • Map<K, V>.[] 的参数应与 K 相关
  • Queue<E>.remove 的参数应与 E 相关
  • Set<E>.lookup 的参数应与 E 相关
  • Set<E>.remove 的参数应与 E 相关

错误

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

错误

dart
void someFunction() {
  var set = <int>{};
  set.remove('1'); // LINT
}

正确

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

正确

dart
void someFunction() {
  var set = <int>{};
  set.remove(1); // OK
}

启用

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - collection_methods_unrelated_type

如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 collection_methods_unrelated_type: true

analysis_options.yaml
yaml
linter:
  rules:
    collection_methods_unrelated_type: true