What is the difference between any() and every() in Dart?

Overview

In Dart, the any() and every() methods have the same syntax and are used to check the items in a list that satisfy a given condition. However, these methods work differently.

The any() method checks if at least one item in the List satisfies the given condition. any() returns a boolean value depending on the condition. In comparison, the every() method checks if all the items in the List satisfy the given condition. every() returns a boolean value depending on the condition.

any() syntax

bool any(bool test(E element));

every() syntax

bool every(bool test(E element));

Code

The following code demonstrates how to use the any() and every() methods in Dart.

void main(){
// Creating list
List numbers = [9, 5, 8, 17, 11, 15, 23];
// Using any()
// verify if at least one item in the list is greater than 7
if (numbers.any((item) => item > 7)) {
// Print result
print('At least one number > 7 in the list');
}
// Using every()
// Checks if all items in the list is less than 4
// stores a boolean value
// depending on the condition
var flag = numbers.every((e) => e<4);
// display result
if (flag) {
print("All items are smaller than 4");
} else {
print("All items are greater than 4");
}
}

Free Resources