The syntax of List.elementAt() method is:
E elementAt(int index)
This elementAt() method of List returns the index
th element.
Parameter | Optional/Required | Description |
---|---|---|
index | required | the index of the element to retrieve |
List.elementAt() returns value of type E
.
In this example,
numbers
containing integers.elementAt()
method with index 2
to retrieve the element at that index.2
is then printed to standard output.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int element = numbers.elementAt(2);
print('Element at index 2: $element');
}
Element at index 2: 3
In this example,
characters
containing characters.elementAt()
method with index 1
to retrieve the element at that index.1
is then printed to standard output.void main() {
List<String> characters = ['a', 'b', 'c'];
String element = characters.elementAt(1);
print('Element at index 1: $element');
}
Element at index 1: b
In this example,
words
containing strings.elementAt()
method with index 0
to retrieve the element at that index.0
is then printed to standard output.void main() {
List<String> words = ['apple', 'banana', 'cherry'];
String element = words.elementAt(0);
print('Element at index 0: $element');
}
Element at index 0: apple
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.