To insert an element at a specific index in a list in Dart, you can use the insert
method of the List
class.
In this example,
numbers
with initial integer values.insert
method to insert a new element at the desired index.insert
method shifts the existing elements to the right to make space for the new element.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.insert(2, 10);
print('Updated list: \$numbers');
}
Updated list: [1, 2, 10, 3, 4, 5]
In this example,
numbers
with initial integer values.insert
method to insert a new element at the beginning of the list.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.insert(0, 10);
print('Updated list: \$numbers');
}
Updated list: [10, 1, 2, 3, 4, 5]
In this tutorial, we learned How to Insert an Element at Specific Index in a List in Dart language with well detailed examples.