any and every
- Dart course
- Intermediate
- Lesson 51/116
- 5 min
Learn condition checks with any and every.
any and every
any and every query elements in a collection. any checks whether at least one element satisfies a condition; every checks whether all elements do. Both return a bool.
Example: [1, 2, 3].any((n) => n > 2) returns true because 3 satisfies it. [1, 2, 3].every((n) => n > 0) returns true because all are positive.
These methods are used for decisions. For example they answer whether there is at least one active user or whether all products are in stock.
Using any and every
These methods are often used in if conditions. any queries the existence of something; every queries whether a property holds for all.
Example: if (cart.any((p) => p.inStock)) print('In stock item found');. Or if (students.every((s) => s.passed)) print('All passed');.
These queries are shorter and more readable than writing a loop. They show the power of the Dart collection API.
Practice Query with any and every
On the list [1, 2, 3, 4, 5] query whether there is an even number with any((n) => n.isEven) and print it. On the same list query whether all are positive with every((n) => n > 0) and print it.
Starter code
void main() {
var numbers = [1, 2, 3, 4, 5];
// check with .any for even, with .every for all positive
// print the results
}Sample solution
void main() {
var numbers = [1, 2, 3, 4, 5];
var hasEven = numbers.any((n) => n.isEven);
var allPos = numbers.every((n) => n > 0);
print(hasEven);
print(allPos);
}Expected output
true true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The any call
var numbers = [1, 2, 3];
var has = numbers.____((n) => n > 2);
var numbers = [1, 2, 3];
var has = numbers.any((n) => n > 2);
Explanation: any checks whether at least one element satisfies the condition.
2 What does [1, 2, 3].every((n) => n > 5) return?
var r = [1, 2, 3].every((n) => n > 5);- true
- It throws
- false Correct answer
- 3
Explanation: no element is greater than 5 so it returns false.
3 Match any and every
| Term | Meaning |
|---|---|
any(...) |
Does at least one satisfy |
every(...) |
Do all satisfy |
true |
Condition met |
false |
Condition not met |