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
.
Parameter | Optional/Required | Description |
---|---|---|
test | required | a function that returns true for elements to include in the output |
List.takeWhile() returns value of type Iterable<E>
.
In this example,
numbers
containing integers from 1 to 10.takeWhile()
method with a test function that checks if a number is even.takeWhile()
method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test.void main() {
List<int> numbers = [2, 4, 6, 7, 8, 9, 10];
var evenNumbers = numbers.takeWhile((number) => number.isEven);
print(evenNumbers.toList());
}
[2, 4, 6]
In this example,
characters
containing lowercase letters.takeWhile()
method with a test function that checks if a character is a vowel (contained in the list ['a', 'e', 'i', 'o', 'u']).takeWhile()
method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test.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());
}
[a]
In this example,
words
containing strings.takeWhile()
method with a test function that checks if the length of a word is less than 6.takeWhile()
method returns a lazy iterable containing all elements from the beginning of the list until the first element fails the test.void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date', 'fig'];
var shortWords = words.takeWhile((word) => word.length < 6);
print(shortWords.toList());
}
[apple]
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.