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
| Parameter | Optional/Required | Description |
|---|---|---|
start | required | the index in this list at which to start setting elements |
end | required | the index in this list before which to stop setting elements |
iterable | required | the iterable object containing elements to be set in this list |
skipCount | optional [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,
- We create a list
numberscontaining integers. - We create another list
replacementcontaining integers to replace elements innumbers. - We use
setRangeto replace elements in the range[1, 3)ofnumberswith elements fromreplacement. - We print the modified
numberslist.
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,
- We create a list
characterscontaining characters. - We create another list
replacementcontaining characters to replace elements incharacters. - We use
setRangeto replace elements in the range[2, 4)ofcharacterswith elements fromreplacement. - We print the modified
characterslist.
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,
- We create a list
wordscontaining strings. - We create another list
replacementcontaining strings to replace elements inwords. - We use
setRangeto replace elements in the range[1, 3)ofwordswith elements fromreplacement. - We print the modified
wordslist.
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.