prefer_contains
Use contains for List
and String
instances.
Details
#DON'T use indexOf
to see if a collection contains an element.
Calling indexOf
to see if a collection contains something is difficult to read and may have poor performance.
Instead, prefer contains
.
BAD:
dart
if (lunchBox.indexOf('sandwich') == -1) return 'so hungry...';
GOOD:
dart
if (!lunchBox.contains('sandwich')) return 'so hungry...';
Enable
#To enable the prefer_contains
rule, add prefer_contains
under linter > rules in your analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- prefer_contains
If you're instead using the YAML map syntax to configure linter rules, add prefer_contains: true
under linter > rules:
analysis_options.yaml
yaml
linter:
rules:
prefer_contains: true
Was this page's content helpful?
Thank you for your feedback!
Provide details Thank you for your feedback! Please let us know what we can do to improve.
Provide details Unless stated otherwise, the documentation on this site reflects Dart 3.8.1. Page last updated on 2025-03-07. View source or report an issue.