The syntax of List.take() method is:
Iterable<E> take(int count)
This take() method of List creates a lazy iterable of the count
first elements of this iterable.
Parameter | Optional/Required | Description |
---|---|---|
count | required | the number of elements to take from the iterable |
List.take() returns value of type Iterable<E>
.
In this example,
numbers
containing the integers 1, 2, 3, 4, 5
.take()
method on numbers
to take the first 3 elements.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
Iterable<int> takenNumbers = numbers.take(3);
print('Taken numbers: $takenNumbers');
}
Taken numbers: (1, 2, 3)
In this example,
characters
containing the strings 'a', 'b', 'c', 'd'
.take()
method on characters
to take the first 2 elements.void main() {
List<String> characters = ['a', 'b', 'c', 'd'];
Iterable<String> takenChars = characters.take(2);
print('Taken characters: $takenChars');
}
Taken characters: (a, b)
In this example,
fruits
containing the strings 'apple', 'banana', 'cherry', 'date'
.take()
method on fruits
to take all elements (4 in this case).void main() {
List<String> fruits = ['apple', 'banana', 'cherry', 'date'];
Iterable<String> takenFruits = fruits.take(4);
print('Taken fruits: $takenFruits');
}
Taken fruits: (apple, banana, cherry, date)
In this Dart tutorial, we learned about take() method of List: the syntax and few working examples with output and detailed explanation for each example.