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
.
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 |
List.replaceRange() returns value of type void
.
In this example,
numbers
containing the integers [1, 2, 3, 4, 5]
.replaceRange()
method to replace elements from index 1 (value 2) to index 3 (value 4) with the elements [6, 7, 8]
.[1, 6, 7, 8, 4, 5]
.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);
}
[1, 6, 7, 8, 4, 5]
In this example,
characters
containing the characters ['a', 'b', 'c', 'd']
.replaceRange()
method to replace elements from index 0 (value 'a') to index 2 (value 'c') with the elements ['x', 'y']
.['x', 'y', 'c', 'd']
.void main() {
List<String> characters = ['a', 'b', 'c', 'd'];
characters.replaceRange(0, 2, ['x', 'y']); // Output: ['x', 'y', 'c', 'd']
print(characters);
}
[x, y, c, d]
In this example,
words
containing the strings ['apple', 'banana', 'cherry', 'date']
.replaceRange()
method to replace elements from index 1 (value 'banana') to index 3 (value 'cherry') with the element ['pear']
.['apple', 'pear', 'date']
.void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date'];
words.replaceRange(1, 3, ['pear']); // Output: ['apple', 'pear', 'date']
print(words);
}
[apple, pear, date]
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.