Dart List takeWhile()
Syntax & Examples


Syntax of List.takeWhile()

The syntax of List.takeWhile() method is:

 Iterable<E> takeWhile(bool test(E value)) 

This takeWhile() method of List creates a lazy iterable of the leading elements satisfying test.

Parameters

ParameterOptional/RequiredDescription
testrequireda function that returns true for elements to include in the output

Return Type

List.takeWhile() returns value of type Iterable<E>.



✐ Examples

1 Take even numbers from a list

In this example,

  1. We create a list named numbers containing integers from 1 to 10.
  2. We use the takeWhile() method with a test function that checks if a number is even.
  3. The takeWhile() method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test.
  4. We convert the lazy iterable to a list and print the result to standard output.

Dart Program

void main() {
  List&lt;int&gt; numbers = [2, 4, 6, 7, 8, 9, 10];
  var evenNumbers = numbers.takeWhile((number) => number.isEven);
  print(evenNumbers.toList());
}

Output

[2, 4, 6]

2 Take vowels from a list of characters

In this example,

  1. We create a list named characters containing lowercase letters.
  2. We use the takeWhile() method with a test function that checks if a character is a vowel (contained in the list ['a', 'e', 'i', 'o', 'u']).
  3. The takeWhile() method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test.
  4. We convert the lazy iterable to a list and print the result to standard output.

Dart Program

void main() {
  List&lt;String&gt; characters = ['a', 'b', 'c', 'd', 'e'];
  var vowels = characters.takeWhile((char) => ['a', 'e', 'i', 'o', 'u'].contains(char));
  print(vowels.toList());
}

Output

[a]

3 Take short words from a list

In this example,

  1. We create a list named words containing strings.
  2. We use the takeWhile() method with a test function that checks if the length of a word is less than 6.
  3. The takeWhile() method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test.
  4. We convert the lazy iterable to a list and print the result to standard output.

Dart Program

void main() {
  List&lt;String&gt; words = ['apple', 'banana', 'cherry', 'date', 'fig'];
  var shortWords = words.takeWhile((word) => word.length &lt; 6);
  print(shortWords.toList());
}

Output

[apple]

Summary

In this Dart tutorial, we learned about takeWhile() method of List: the syntax and few working examples with output and detailed explanation for each example.