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 the index of the item.

Note: The index must be non-negative and less than the list’s length. Otherwise, the RangeError exception will be thrown.

Return value

This method returns the element that is present at the specified index.

Code

void main(){
// Create list name
List name = ['John', 'Hamad', 'Maria', 'Rejoice', 'Elena'];
// Accessing element at index 3
// Using elementAt() method
var element = name.elementAt(3);
// Display result
print('The element at index 3 is ${element}');
// Accessing element the first element
// Using elementAt() method
var element2 = name.elementAt(0);
// Display result
print('The first element in the list is ${element2}');
// try to access a negative index
try
{
var element3 = name.elementAt(-2);
// Display result
print('The element in the list is at index -1 is ${element2}');
}
on RangeError {
// code for handling exception
print('Out of bound index error occurred');
}
// try to get the index beyond the list size
try
{
var element3 = name.elementAt(10);
// Display result
print('The element in the list is at index -1 is ${element2}');
}
on RangeError {
// code for handling exception
print('Out of bound index error occurred');
}
}

Explanation

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.

Free Resources