Dart Tutorials

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

ParameterOptional/RequiredDescription
indexrequiredthe position at which to insert the elements
iterablerequiredthe iterable containing objects to insert

Return Type

List.insertAll() returns value of type void.



✐ Examples

1 Insert numbers into a list

In this example,

  1. We create a list named numbers with elements [1, 2, 3, 4].
  2. We also create a list named toInsert with elements [5, 6, 7].
  3. We then use the insertAll() method to insert all elements of toInsert into numbers starting at index 2.
  4. 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,

  1. We create a list named characters with elements ['a', 'b', 'c'].
  2. We also create a list named toInsert with elements ['x', 'y', 'z'].
  3. We then use the insertAll() method to insert all elements of toInsert into characters starting at index 1.
  4. 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,

  1. We create a list named fruits with elements ['apple', 'banana', 'cherry'].
  2. We also create a list named toInsert with elements ['orange', 'grapes'].
  3. We then use the insertAll() method to insert all elements of toInsert into fruits starting at index 0.
  4. 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.