Dart Tutorials

Dart List elementAt()
Syntax & Examples

Syntax of List.elementAt()

The syntax of List.elementAt() method is:

 E elementAt(int index) 

This elementAt() method of List returns the indexth element.

Parameters

ParameterOptional/RequiredDescription
indexrequiredthe index of the element to retrieve

Return Type

List.elementAt() returns value of type E.



✐ Examples

1 Retrieve element at index 2 from a list of numbers

In this example,

  1. We create a list named numbers containing integers.
  2. We use the elementAt() method with index 2 to retrieve the element at that index.
  3. The element at index 2 is then printed to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  int element = numbers.elementAt(2);
  print('Element at index 2: $element');
}

Output

Element at index 2: 3

2 Retrieve element at index 1 from a list of characters

In this example,

  1. We create a list named characters containing characters.
  2. We use the elementAt() method with index 1 to retrieve the element at that index.
  3. The element at index 1 is then printed to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c'];
  String element = characters.elementAt(1);
  print('Element at index 1: $element');
}

Output

Element at index 1: b

3 Retrieve element at index 0 from a list of words

In this example,

  1. We create a list named words containing strings.
  2. We use the elementAt() method with index 0 to retrieve the element at that index.
  3. The element at index 0 is then printed to standard output.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry'];
  String element = words.elementAt(0);
  print('Element at index 0: $element');
}

Output

Element at index 0: apple

Summary

In this Dart tutorial, we learned about elementAt() method of List: the syntax and few working examples with output and detailed explanation for each example.