The insertAll()
method in Dart is used to insert elements at a specific index in the list, which shifts the following elements by the number of the elements to be inserted.
void insertAll(
int index,
Iterable<E> element
);
index
: the position where the element will be inserted.Iterable<E> element
: the elements 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 return type for this function is void.
The following code shows how to use the insertAll()
method in Dart.
void main(){// Create List fruitsList<String> fruits = ['Mango', 'Pawpaw', 'Avocado', 'Pineapple', 'Lemon'];// Display resultprint("Original list $fruits");// Another listList<String> newFruits = ['Apple', 'Orange'];// Insert new items in the list// using insertAll()fruits.insertAll(2, newFruits);// Display resultprint('The new list: ${fruits}');}
The list’s length is increased by the number of elements to be inserted.
We create two lists named fruits
and newFruits
. We use the insertAll()
method to insert all of the elements in newfruits
in fruits
, then display the result.
Note: Passing an invalid index will throw the
RangeError
exception.