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
numbers
containing integers. - We create another list
replacement
containing integers to replace elements innumbers
. - We use
setRange
to replace elements in the range[1, 3)
ofnumbers
with elements fromreplacement
. - 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,
- We create a list
characters
containing characters. - We create another list
replacement
containing characters to replace elements incharacters
. - We use
setRange
to replace elements in the range[2, 4)
ofcharacters
with elements fromreplacement
. - 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,
- We create a list
words
containing strings. - We create another list
replacement
containing strings to replace elements inwords
. - We use
setRange
to replace elements in the range[1, 3)
ofwords
with elements fromreplacement
. - 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.