Skip to main content

avoid-unsafe-reduce

added in: 1.18.0
Pro+

Warns when the .reduce collection method is called on a potentially empty collection.

Calling .reduce on an empty collection will result in a runtime exception.

Example

❌ Bad:

void fn() {
final list = <int>[];
final sum = list.reduce((a, b) => a + b); // LINT: Calling 'reduce' on an empty collection will throw an exception. Try checking if this collection is not empty first.
}

✅ Good:

void fn() {
final list = <int>[];

final sum = list.isEmpty ? null : list.reduce((a, b) => a + b); // Correct, has a length check first

// OR

if (list.isNotEmpty) {
final sum = list.reduce((a, b) => a + b);
}
}

Additional Resources