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.
list_name.elementAt(
int index
);
index: This represents the index of the item.Note: The index must be non-negative and less than the list’s length. Otherwise, the
RangeErrorexception will be thrown.
This method returns the element that is present at the specified index.
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');}}
In the code above:
In line 3, we declare an array name with 5 elements.
In lines 7 and 13, we get an element from the name list, using the elementAt method from indexes 3 and 0.
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 the name list. Hence, an exception is thrown, which is caught at line 37.