Skip to main content

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:

dart
void f(List<String> l, String s) {
  if (l.indexOf(s) < 0) {
    // ...
  }
}

Common fixes

#

Use contains instead, negating the condition when necessary:

dart
void f(List<String> l, String s) {
  if (l.contains(s)) {
    // ...
  }
}