Dart Tutorials

Dart List setRange()
Syntax & Examples

Syntax of List.setRange()

The syntax of List.setRange() method is:

 void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) 

This setRange() method of List writes some elements of iterable into a range of this list.

Parameters

ParameterOptional/RequiredDescription
startrequiredthe index in this list at which to start setting elements
endrequiredthe index in this list before which to stop setting elements
iterablerequiredthe iterable object containing elements to be set in this list
skipCountoptional [default value is 0]the number of elements to skip in the iterable before setting elements in this list

Return Type

List.setRange() returns value of type void.



✐ Examples

1 Set range in a list of numbers

In this example,

  1. We create a list numbers containing integers.
  2. We create another list replacement containing integers to replace elements in numbers.
  3. We use setRange to replace elements in the range [1, 3) of numbers with elements from replacement.
  4. We print the modified numbers list.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  List<int> replacement = [10, 20];
  numbers.setRange(1, 3, replacement);
  print(numbers);
}

Output

[1, 10, 20, 4, 5]

2 Set range in a list of characters

In this example,

  1. We create a list characters containing characters.
  2. We create another list replacement containing characters to replace elements in characters.
  3. We use setRange to replace elements in the range [2, 4) of characters with elements from replacement.
  4. We print the modified characters list.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd', 'e'];
  List<String> replacement = ['x', 'y', 'z'];
  characters.setRange(2, 4, replacement);
  print(characters);
}

Output

[a, b, x, y, e]

3 Set range in a list of words

In this example,

  1. We create a list words containing strings.
  2. We create another list replacement containing strings to replace elements in words.
  3. We use setRange to replace elements in the range [1, 3) of words with elements from replacement.
  4. We print the modified words list.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry', 'date'];
  List<String> replacement = ['grape', 'kiwi'];
  words.setRange(1, 3, replacement);
  print(words);
}

Output

[apple, grape, kiwi, date]

Summary

In this Dart tutorial, we learned about setRange() method of List: the syntax and few working examples with output and detailed explanation for each example.