Dart List replaceRange()
Syntax & Examples
Syntax of List.replaceRange()
The syntax of List.replaceRange() method is:
void replaceRange(int start, int end, Iterable<E> replacements)
This replaceRange() method of List replaces a range of elements with the elements of replacements
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
start | required | the starting index of the range to be replaced in the list |
end | required | the ending index of the range to be replaced in the list (exclusive) |
replacements | required | an iterable containing the elements to replace the specified range |
Return Type
List.replaceRange() returns value of type void
.
✐ Examples
1 Replace elements from index 1 to 2 with [6, 7, 8] in the list of numbers
In this example,
- We create a list named
numbers
containing the integers[1, 2, 3, 4, 5]
. - We then use the
replaceRange()
method to replace elements from index 1 (value 2) to index 3 (value 4) with the elements[6, 7, 8]
. - As a result, the list becomes
[1, 6, 7, 8, 4, 5]
. - We print the modified list to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.replaceRange(1, 3, [6, 7, 8]); // Output: [1, 6, 7, 8, 4, 5]
print(numbers);
}
Output
[1, 6, 7, 8, 4, 5]
2 Replace elements from index 0 to 1 with ['x', 'y'] in the list of characters
In this example,
- We create a list named
characters
containing the characters['a', 'b', 'c', 'd']
. - We then use the
replaceRange()
method to replace elements from index 0 (value 'a') to index 2 (value 'c') with the elements['x', 'y']
. - As a result, the list becomes
['x', 'y', 'c', 'd']
. - We print the modified list to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c', 'd'];
characters.replaceRange(0, 2, ['x', 'y']); // Output: ['x', 'y', 'c', 'd']
print(characters);
}
Output
[x, y, c, d]
3 Replace elements from index 1 to 2 with ['pear'] in the list of words
In this example,
- We create a list named
words
containing the strings['apple', 'banana', 'cherry', 'date']
. - We then use the
replaceRange()
method to replace elements from index 1 (value 'banana') to index 3 (value 'cherry') with the element['pear']
. - As a result, the list becomes
['apple', 'pear', 'date']
. - We print the modified list to standard output.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date'];
words.replaceRange(1, 3, ['pear']); // Output: ['apple', 'pear', 'date']
print(words);
}
Output
[apple, pear, date]
Summary
In this Dart tutorial, we learned about replaceRange() method of List: the syntax and few working examples with output and detailed explanation for each example.