Dart Tutorials

Dart List insert()
Syntax & Examples

Syntax of List.insert()

The syntax of List.insert() method is:

 void insert(int index, E element) 

This insert() method of List inserts element at position index in this list.

Parameters

ParameterOptional/RequiredDescription
indexrequiredthe position where the element will be inserted
elementrequiredthe element to be inserted at the specified index

Return Type

List.insert() returns value of type void.



✐ Examples

1 Insert an element into a list of numbers

In this example,

  1. We create a list named numbers containing the numbers [1, 2, 3, 4, 5].
  2. We then use the insert() method to insert the number 10 at index 2.
  3. The modified list is printed to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  numbers.insert(2, 10); // Output: [1, 2, 10, 3, 4, 5]
  print(numbers);
}

Output

[1, 2, 10, 3, 4, 5]

2 Insert an element into a list of characters

In this example,

  1. We create a list named characters containing the characters ['a', 'b', 'c', 'd', 'e'].
  2. We then use the insert() method to insert the character 'x' at index 3.
  3. The modified list is printed to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd', 'e'];
  characters.insert(3, 'x'); // Output: [a, b, c, x, d, e]
  print(characters);
}

Output

[a, b, c, x, d, e]

3 Insert an element into a list of strings

In this example,

  1. We create a list named strings containing the strings ['apple', 'banana', 'cherry'].
  2. We then use the insert() method to insert the string 'orange' at index 1.
  3. The modified list is printed to standard output.

Dart Program

void main() {
  List<String> strings = ['apple', 'banana', 'cherry'];
  strings.insert(1, 'orange'); // Output: [apple, orange, banana, cherry]
  print(strings);
}

Output

[apple, orange, banana, cherry]

Summary

In this Dart tutorial, we learned about insert() method of List: the syntax and few working examples with output and detailed explanation for each example.