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
Parameter | Optional/Required | Description |
---|---|---|
test | required | a 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,
- We create a list named
numbers
containing integers from 1 to 10. - We use the
takeWhile()
method with a test function that checks if a number is even. - The
takeWhile()
method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test. - We convert the lazy iterable to a list and print the result to standard output.
Dart Program
void main() {
List<int> 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,
- We create a list named
characters
containing lowercase letters. - 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']). - The
takeWhile()
method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test. - We convert the lazy iterable to a list and print the result to standard output.
Dart Program
void main() {
List<String> 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,
- We create a list named
words
containing strings. - We use the
takeWhile()
method with a test function that checks if the length of a word is less than 6. - The
takeWhile()
method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test. - We convert the lazy iterable to a list and print the result to standard output.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date', 'fig'];
var shortWords = words.takeWhile((word) => word.length < 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.