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.
Parameter | Optional/Required | Description |
---|---|---|
index | required | the position where the element will be inserted |
element | required | the element to be inserted at the specified index |
List.insert() returns value of type void
.
In this example,
numbers
containing the numbers [1, 2, 3, 4, 5]
.insert()
method to insert the number 10
at index 2
.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.insert(2, 10); // Output: [1, 2, 10, 3, 4, 5]
print(numbers);
}
[1, 2, 10, 3, 4, 5]
In this example,
characters
containing the characters ['a', 'b', 'c', 'd', 'e']
.insert()
method to insert the character 'x'
at index 3
.void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
characters.insert(3, 'x'); // Output: [a, b, c, x, d, e]
print(characters);
}
[a, b, c, x, d, e]
In this example,
strings
containing the strings ['apple', 'banana', 'cherry']
.insert()
method to insert the string 'orange'
at index 1
.void main() {
List<String> strings = ['apple', 'banana', 'cherry'];
strings.insert(1, 'orange'); // Output: [apple, orange, banana, cherry]
print(strings);
}
[apple, orange, banana, cherry]
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.