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
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 |
Return Type
List.insert() returns value of type void
.
✐ Examples
1 Insert an element into a list of numbers
In this example,
- We create a list named
numbers
containing the numbers[1, 2, 3, 4, 5]
. - We then use the
insert()
method to insert the number10
at index2
. - 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,
- We create a list named
characters
containing the characters['a', 'b', 'c', 'd', 'e']
. - We then use the
insert()
method to insert the character'x'
at index3
. - 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,
- We create a list named
strings
containing the strings['apple', 'banana', 'cherry']
. - We then use the
insert()
method to insert the string'orange'
at index1
. - 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.