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
numbers
with elements [1, 2, 3, 4]. - We also create a list named
toInsert
with elements [5, 6, 7]. - We then use the
insertAll()
method to insert all elements oftoInsert
intonumbers
starting at index 2. - The resulting list
numbers
is 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
characters
with elements ['a', 'b', 'c']. - We also create a list named
toInsert
with elements ['x', 'y', 'z']. - We then use the
insertAll()
method to insert all elements oftoInsert
intocharacters
starting at index 1. - The resulting list
characters
is 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
fruits
with elements ['apple', 'banana', 'cherry']. - We also create a list named
toInsert
with elements ['orange', 'grapes']. - We then use the
insertAll()
method to insert all elements oftoInsert
intofruits
starting at index 0. - The resulting list
fruits
is 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.