What is the List elementAt() method in Dart?
In Dart, the elementAt() method is used to access the item at a specified index in a List. It returns the element at the specified index.
Syntax
list_name.elementAt(
int index
);
Parameter
index: This represents theindexof the item.
Note: The index must be non-negative and less than the list’s length. Otherwise, the
RangeErrorexception will be thrown.
Return value
This method returns the element that is present at the specified index.
Code
void main(){// Create list nameList name = ['John', 'Hamad', 'Maria', 'Rejoice', 'Elena'];// Accessing element at index 3// Using elementAt() methodvar element = name.elementAt(3);// Display resultprint('The element at index 3 is ${element}');// Accessing element the first element// Using elementAt() methodvar element2 = name.elementAt(0);// Display resultprint('The first element in the list is ${element2}');// try to access a negative indextry{var element3 = name.elementAt(-2);// Display resultprint('The element in the list is at index -1 is ${element2}');}on RangeError {// code for handling exceptionprint('Out of bound index error occurred');}// try to get the index beyond the list sizetry{var element3 = name.elementAt(10);// Display resultprint('The element in the list is at index -1 is ${element2}');}on RangeError {// code for handling exceptionprint('Out of bound index error occurred');}}
Explanation
In the code above:
-
In line 3, we declare an array
namewith 5 elements. -
In lines 7 and 13, we get an element from the
namelist, using theelementAtmethod from indexes3and0. -
In line 20, we try to access the element at index
-2, which is a non-existent index. Hence, an exception is thrown, which is caught at line 24. -
In line 33, we try to access the element at index
10, which is beyond the size of thenamelist. Hence, an exception is thrown, which is caught at line 37.