collection_methods_unrelated_type
使用不相關型別的引數調用各種集合方法。
此規則自 Dart 2.19 起提供。
詳細資訊
#不要使用不相關型別的引數調用某些集合方法。
這樣做會在集合的元素上調用 ==
,並且很可能會傳回 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
除非另有說明,否則此網站上的文件反映 Dart 3.6.0。頁面最後更新於 2024-07-03。 檢視原始碼 或 回報問題。