Skip to main content

avoid-unsafe-reduce

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>[];
// LINT: Calling 'reduce' on an empty collection will throw an exception.
// Try checking if this collection is not empty first.
final sum = list.reduce((a, b) => a + b);
}

✅ 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