Dart Set any()
Syntax & Examples
Syntax of Set.any()
The syntax of Set.any() method is:
bool any(bool test(E element))
This any() method of Set checks whether any element of this iterable satisfies test.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
test | required | A function that takes an element of the iterable and returns a boolean value. |
Return Type
Set.any() returns value of type bool
.
✐ Examples
1 Checking if any number is even
In this example,
- We create a List
numbers
with values [1, 2, 3, 4, 5]. - We use the
any()
method with a test function that checks if an element is even. - We print the result, which indicates if any number in the list is even.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
bool isAnyEven = numbers.any((element) => element.isEven);
print(isAnyEven);
}
Output
true
2 Checking for short words
In this example,
- We create a List
words
with values ['apple', 'banana', 'cherry']. - We use the
any()
method with a test function that checks if a word's length is less than 5. - We print the result, which indicates if there's any short word in the list.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'cherry'];
bool hasShortWord = words.any((element) => element.length < 5);
print(hasShortWord);
}
Output
true
Summary
In this Dart tutorial, we learned about any() method of Set: the syntax and few working examples with output and detailed explanation for each example.