Dart List any()
Syntax & Examples


Syntax of List.any()

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.

Parameters

ParameterOptional/RequiredDescription
testrequiredthe function used to test each element

Return Type

List.any() returns value of type bool.



✐ Examples

1 Check if list contains positive numbers

In this example,

  1. We create a list numbers containing integers [1, 2, 3].
  2. We use the any() method with a test function that checks if each element is greater than 0.
  3. The result indicates whether the list contains any positive numbers.
  4. We print the result to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3];
  bool hasPositive = numbers.any((element) => element > 0);
  print('Has positive number: $hasPositive');
}

Output

Has positive number: true

2 Check if list contains vowels

In this example,

  1. We create a list characters containing characters ['a', 'b', 'c'].
  2. We use the any() method with a test function that checks if each element is a vowel.
  3. The result indicates whether the list contains any vowels.
  4. We print the result to standard output.

Dart Program

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');
}

Output

Has vowel: true

3 Check if list contains a word with length > 5

In this example,

  1. We create a list words containing strings ['hello', 'world'].
  2. We use the any() method with a test function that checks if any word has a length greater than 5.
  3. The result indicates whether the list contains such a word.
  4. We print the result to standard output.

Dart Program

void main() {
  List<String> words = ['hello', 'world'];
  bool hasLongWord = words.any((element) => element.length > 5);
  print('Has word with length > 5: $hasLongWord');
}

Output

Has word with length > 5: false

Summary

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.