prefer_is_empty

Stable
Core
Fix available

Use isEmpty for Iterables and Maps.

Details

#

DON'T use length to see if a collection is empty.

The Iterable contract does not require that a collection know its length or be able to provide it in constant time. Calling length just to see if the collection contains anything can be painfully slow.

Instead, there are faster and more readable getters: isEmpty and isNotEmpty. Use the one that doesn't require you to negate the result.

BAD:

dart
if (lunchBox.length == 0) return 'so hungry...';
if (words.length != 0) return words.join(' ');

GOOD:

dart
if (lunchBox.isEmpty) return 'so hungry...';
if (words.isNotEmpty) return words.join(' ');

Enable

#

To enable the prefer_is_empty rule, add prefer_is_empty under linter > rules in your analysis_options.yaml file:

analysis_options.yaml
yaml
linter:
  rules:
    - prefer_is_empty

If you're instead using the YAML map syntax to configure linter rules, add prefer_is_empty: true under linter > rules:

analysis_options.yaml
yaml
linter:
  rules:
    prefer_is_empty: true