The syntax of List.any() method is:
bool any(bool test(E element))
This any() method of List checks whether any element of this iterable satisfies test
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | the function used to test each element |
List.any() returns value of type bool
.
In this example,
numbers
containing integers [1, 2, 3].any()
method with a test function that checks if each element is greater than 0.void main() {
List<int> numbers = [1, 2, 3];
bool hasPositive = numbers.any((element) => element > 0);
print('Has positive number: $hasPositive');
}
Has positive number: true
In this example,
characters
containing characters ['a', 'b', 'c'].any()
method with a test function that checks if each element is a vowel.void main() {
List<String> characters = ['a', 'b', 'c'];
bool hasVowel = characters.any((element) => element == 'a' || element == 'e' || element == 'i' || element == 'o' || element == 'u');
print('Has vowel: $hasVowel');
}
Has vowel: true
In this example,
words
containing strings ['hello', 'world'].any()
method with a test function that checks if any word has a length greater than 5.void main() {
List<String> words = ['hello', 'world'];
bool hasLongWord = words.any((element) => element.length > 5);
print('Has word with length > 5: $hasLongWord');
}
Has word with length > 5: false
In this Dart tutorial, we learned about any() method of List: the syntax and few working examples with output and detailed explanation for each example.