Dart List take()
Syntax & Examples
Syntax of List.take()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
count | required | the number of elements to take from the iterable |
Return Type
List.take() returns value of type Iterable<E>
.
✐ Examples
1 Take first 3 numbers from the list
In this example,
- We create a list named
numbers
containing the integers1, 2, 3, 4, 5
. - We then use the
take()
method onnumbers
to take the first 3 elements. - The result is an iterable containing the taken numbers.
- We print the taken numbers to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
Iterable<int> takenNumbers = numbers.take(3);
print('Taken numbers: $takenNumbers');
}
Output
Taken numbers: (1, 2, 3)
2 Take first 2 characters from the list
In this example,
- We create a list named
characters
containing the strings'a', 'b', 'c', 'd'
. - We then use the
take()
method oncharacters
to take the first 2 elements. - The result is an iterable containing the taken characters.
- We print the taken characters to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c', 'd'];
Iterable<String> takenChars = characters.take(2);
print('Taken characters: $takenChars');
}
Output
Taken characters: (a, b)
3 Take all fruits from the list
In this example,
- We create a list named
fruits
containing the strings'apple', 'banana', 'cherry', 'date'
. - We then use the
take()
method onfruits
to take all elements (4 in this case). - The result is an iterable containing all the fruits.
- We print the taken fruits to standard output.
Dart Program
void main() {
List<String> fruits = ['apple', 'banana', 'cherry', 'date'];
Iterable<String> takenFruits = fruits.take(4);
print('Taken fruits: $takenFruits');
}
Output
Taken fruits: (apple, banana, cherry, date)
Summary
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.