Dart List every()
Syntax & Examples
Syntax of List.every()
The syntax of List.every() method is:
bool every(bool test(E element))
This every() method of List checks whether every element of this iterable satisfies test
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
test | required | a function that takes an element and returns a boolean value |
Return Type
List.every() returns value of type bool
.
✐ Examples
1 Check if all numbers in the list are positive
In this example,
- We create a list named
numbers
containing the numbers1, 2, 3, 4, 5
. - We then use the
every()
method to check if all elements innumbers
are greater than0
. - The result, indicating whether all numbers are positive, is printed to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
bool allPositive = numbers.every((element) => element > 0);
print('All numbers are positive: $allPositive'); // Output: All numbers are positive: true
}
Output
All numbers are positive: true
2 Check if all characters in the list are lowercase
In this example,
- We create a list named
characters
containing the characters'a', 'b', 'c', 'd'
. - We then use the
every()
method to check if all characters incharacters
are lowercase by comparing each character to its lowercase equivalent. - The result, indicating whether all characters are lowercase, is printed to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c', 'd'];
bool allLowerCase = characters.every((element) => element == element.toLowerCase());
print('All characters are lowercase: $allLowerCase'); // Output: All characters are lowercase: true
}
Output
All characters are lowercase: true
3 Check if all words in the list are longer than four characters
In this example,
- We create a list named
words
containing the strings'apple', 'banana', 'orange'
. - We then use the
every()
method to check if all words inwords
have a length greater than4
. - The result, indicating whether all words are longer than four characters, is printed to standard output.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'orange'];
bool allLongerThanFour = words.every((element) => element.length > 4);
print('All words are longer than four characters: $allLongerThanFour'); // Output: All words are longer than four characters: false
}
Output
All words are longer than four characters: false
Summary
In this Dart tutorial, we learned about every() method of List: the syntax and few working examples with output and detailed explanation for each example.