Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

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

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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");
}
}
Implementation of the "any()" and "every()" methods

RELATED TAGS

dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring