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

ParameterOptional/RequiredDescription
testrequireda 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,

  1. We create a list named numbers containing the numbers 1, 2, 3, 4, 5.
  2. We then use the every() method to check if all elements in numbers are greater than 0.
  3. 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,

  1. We create a list named characters containing the characters 'a', 'b', 'c', 'd'.
  2. We then use the every() method to check if all characters in characters are lowercase by comparing each character to its lowercase equivalent.
  3. 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,

  1. We create a list named words containing the strings 'apple', 'banana', 'orange'.
  2. We then use the every() method to check if all words in words have a length greater than 4.
  3. 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.