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 index
th element.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
index | required | the 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,
- We create a list named
numbers
containing integers. - We use the
elementAt()
method with index2
to retrieve the element at that index. - 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,
- We create a list named
characters
containing characters. - We use the
elementAt()
method with index1
to retrieve the element at that index. - 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,
- We create a list named
words
containing strings. - We use the
elementAt()
method with index0
to retrieve the element at that index. - 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.