跳到主要內容

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