Dart Tutorials

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

ParameterOptional/RequiredDescription
countrequiredthe 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,

  1. We create a list named numbers containing the integers 1, 2, 3, 4, 5.
  2. We then use the take() method on numbers to take the first 3 elements.
  3. The result is an iterable containing the taken numbers.
  4. 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,

  1. We create a list named characters containing the strings 'a', 'b', 'c', 'd'.
  2. We then use the take() method on characters to take the first 2 elements.
  3. The result is an iterable containing the taken characters.
  4. 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,

  1. We create a list named fruits containing the strings 'apple', 'banana', 'cherry', 'date'.
  2. We then use the take() method on fruits to take all elements (4 in this case).
  3. The result is an iterable containing all the fruits.
  4. 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.