Dart – If All Elements in List satisfy given Condition
To check if all of the elements from a List satisfy a given test/condition in Dart, call every()
method on this list and pass the test function as argument. every()
method returns true
if all the elements return true
for given test function, or else it returns false
if any of the elements returns false
for given test function.
The test function must take the element as argument and return a boolean value.
Syntax
The syntax to call every()
method on the List list
with test function test
passed as argument is
list.every(test)
Example
In this example, we take a list of integers, and check if all these integers are even numbers, using List.every()
method. The test function is a lambda function that takes an integer and returns true
if the integer is even number, or false
if not.
main.dart
bool isEven(int n) => (n % 2 == 0);
void main() {
var list = [2, 4, 8, 16, 32];
var result = list.any(isEven);
print('Are all even numbers : $result');
}
Output
Are all even numbers : true
Conclusion
In this Dart Tutorial, we learned how to check if all elements from the list satisfies given test function, with examples.