Dart – Get Element at Specific Index
To get an element at specific index from a List in Dart, call elementAt()
method on this list and pass the index as argument. elementAt()
method returns the element.
If the index is out of range for the list, then elementAt()
throws RangeError
.
Syntax
The syntax to get element at specific index index
from the List list
is
list.elementAt(index)
Examples
In this example, we take a list of integers with five elements, and get elements at index 3, using List.elementAt()
method.
main.dart
void main() {
var list = [2, 4, 8, 16, 32];
var element = list.elementAt(3);
print('Element : $element');
}
Output
Element : 16
RangeError Scenario
In this example, we take a list of integers with five elements, and get elements at index 7, using List.elementAt()
method. Since the index is out of bounds from given list, elementAt()
throws RangeError
.
main.dart
void main() {
var list = [2, 4, 8, 16, 32];
var element = list.elementAt(7);
print('Element : $element');
}
Output
Unhandled exception:
RangeError (index): Invalid value: Not in inclusive range 0..4: 7
#0 List.[] (dart:core-patch/growable_array.dart:260:36)
#1 List.elementAt (dart:core-patch/growable_array.dart:483:16)
#2 main (file:///Users/tutorialkart/Desktop/Projects/DartTutorial/main.dart:3:22)
#3 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
Conclusion
In this Dart Tutorial, we learned how to get an element from a list at specified index, with examples.