What is the List insert() method in Dart?
List insert() method
The 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.
Syntax
list_name.insert(int index, E element);
Parameters
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.
Return value
The insert() method does not return anything.
Example
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.
Explanation
- Line 3: We create a
listnamedfruits. - Line 5: We print the items in the
list. - Line 8: We use the method
insert()to add a new item at index2. - Line 10: Finally, the result is printed.
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
indexvalue will throw aRangeErrorexception.