Dart List insertAll()
Syntax & Examples
Syntax of List.insertAll()
The syntax of List.insertAll() method is:
void insertAll(int index, Iterable<E> iterable) This insertAll() method of List inserts all objects of iterable at position index in this list.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
index | required | the position at which to insert the elements |
iterable | required | the iterable containing objects to insert |
Return Type
List.insertAll() returns value of type void.
✐ Examples
1 Insert numbers into a list
In this example,
- We create a list named
numberswith elements [1, 2, 3, 4]. - We also create a list named
toInsertwith elements [5, 6, 7]. - We then use the
insertAll()method to insert all elements oftoInsertintonumbersstarting at index 2. - The resulting list
numbersis printed to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4];
List<int> toInsert = [5, 6, 7];
numbers.insertAll(2, toInsert);
print(numbers);
}Output
[1, 2, 5, 6, 7, 3, 4]
2 Insert characters into a list
In this example,
- We create a list named
characterswith elements ['a', 'b', 'c']. - We also create a list named
toInsertwith elements ['x', 'y', 'z']. - We then use the
insertAll()method to insert all elements oftoInsertintocharactersstarting at index 1. - The resulting list
charactersis printed to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c'];
List<String> toInsert = ['x', 'y', 'z'];
characters.insertAll(1, toInsert);
print(characters);
}Output
[a, x, y, z, b, c]
3 Insert fruits into a list
In this example,
- We create a list named
fruitswith elements ['apple', 'banana', 'cherry']. - We also create a list named
toInsertwith elements ['orange', 'grapes']. - We then use the
insertAll()method to insert all elements oftoInsertintofruitsstarting at index 0. - The resulting list
fruitsis printed to standard output.
Dart Program
void main() {
List<String> fruits = ['apple', 'banana', 'cherry'];
List<String> toInsert = ['orange', 'grapes'];
fruits.insertAll(0, toInsert);
print(fruits);
}Output
[orange, grapes, apple, banana, cherry]
Summary
In this Dart tutorial, we learned about insertAll() method of List: the syntax and few working examples with output and detailed explanation for each example.