insert()
methodThe insert()
method in Dart is used to insert an element at a specific index in the list. This increases the list’s length by one and moves all elements after the index towards the end of the list.
list_name.insert(int index, E element);
index
: Specifies the index where the element will be inserted in the list.element
: Represents the value to be inserted.Note: The index value must be valid. The valid index ranges from 0…N, where N is the number of elements in the list.
The insert()
method does not return anything.
The following code shows how to use the insert()
method in Dart:
void main(){// Create List fruitsList<String> fruits = ['Mango', 'Pawpaw', 'Avocado', 'Pineapple', 'Lemon'];// Display resultprint("Original list $fruits");// Insert new item in the list// using insert()fruits.insert(2, "Apple");// Display resultprint('The new list: ${fruits}');}
Note: The length of the list will increase by one each time the method
insert()
is used.
list
named fruits
.list
.insert()
to add a new item at index 2
.As indexing starts at 0, the above code will insert Apple
as the third element, shifting Avocado
, Pineapple
, and Lemon
to the right by one position.
Note: Passing an invalid
index
value will throw aRangeError
exception.