prefer_contains
Always 'false' because 'indexOf' is always greater than or equal to -1.
Always 'true' because 'indexOf' is always greater than or equal to -1.
Unnecessary use of 'indexOf' to test for containment.
Description
#The analyzer produces this diagnostic when the method indexOf
is used and the result is only compared with -1
or 0
in a way where the semantics are equivalent to using contains
.
Example
#The following code produces this diagnostic because the condition in the if
statement is checking to see whether the list contains the string:
void f(List<String> l, String s) {
if (l.indexOf(s) < 0) {
// ...
}
}
Common fixes
#Use contains
instead, negating the condition when necessary:
void f(List<String> l, String s) {
if (l.contains(s)) {
// ...
}
}
Unless stated otherwise, the documentation on this site reflects Dart 3.7.3. Page last updated on 2025-05-08. View source or report an issue.