Dart Tutorials

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

ParameterOptional/RequiredDescription
startrequiredthe starting index of the range to be replaced in the list
endrequiredthe ending index of the range to be replaced in the list (exclusive)
replacementsrequiredan 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,

  1. We create a list named numbers containing the integers [1, 2, 3, 4, 5].
  2. 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].
  3. As a result, the list becomes [1, 6, 7, 8, 4, 5].
  4. We print the modified list to standard output.

Dart Program

void main() {
  List&lt;int&gt; 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,

  1. We create a list named characters containing the characters ['a', 'b', 'c', 'd'].
  2. We then use the replaceRange() method to replace elements from index 0 (value 'a') to index 2 (value 'c') with the elements ['x', 'y'].
  3. As a result, the list becomes ['x', 'y', 'c', 'd'].
  4. We print the modified list to standard output.

Dart Program

void main() {
  List&lt;String&gt; 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,

  1. We create a list named words containing the strings ['apple', 'banana', 'cherry', 'date'].
  2. We then use the replaceRange() method to replace elements from index 1 (value 'banana') to index 3 (value 'cherry') with the element ['pear'].
  3. As a result, the list becomes ['apple', 'pear', 'date'].
  4. We print the modified list to standard output.

Dart Program

void main() {
  List&lt;String&gt; 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.