Dart List fillRange()
Syntax & Examples
Syntax of List.fillRange()
The syntax of List.fillRange() method is:
void fillRange(int start, int end, [E? fillValue])
This fillRange() method of List overwrites a range of elements with fillValue
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
start | required | the start index of the range to fill |
end | required | the end index of the range to fill |
fillValue | optional | the value used to fill the range, defaults to null if not provided |
Return Type
List.fillRange() returns value of type void
.
✐ Examples
1 Fill range with zeros
In this example,
- We create a list named
numbers
containing the numbers1, 2, 3, 4, 5
. - We then use the
fillRange()
method to fill the range from index1
to3
with zeros. - The modified list is printed to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.fillRange(1, 3, 0);
print('Filled range with zeros: $numbers'); // Output: Filled range with zeros: [1, 0, 0, 4, 5]
}
Output
Filled range with zeros: [1, 0, 0, 4, 5]
2 Fill range with 'x'
In this example,
- We create a list named
characters
containing the characters'a', 'b', 'c', 'd', 'e'
. - We then use the
fillRange()
method to fill the range from index2
to4
with the character'x'
. - The modified list is printed to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
characters.fillRange(2, 4, 'x');
print('Filled range with \'x\': $characters'); // Output: Filled range with 'x': [a, b, x, x, e]
}
Output
Filled range with 'x': [a, b, x, x, e]
3 Fill range with 'orange'
In this example,
- We create a list named
words
containing the strings'apple', 'banana', 'cherry', 'date', 'fig'
. - We then use the
fillRange()
method to fill the range from index1
to4
with the string'orange'
. - The modified list is printed to standard output.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date', 'fig'];
words.fillRange(1, 4, 'orange');
print('Filled range with \'orange\': $words'); // Output: Filled range with 'orange': [apple, orange, orange, orange, fig]
}
Output
Filled range with 'orange': [apple, orange, orange, orange, fig]
Summary
In this Dart tutorial, we learned about fillRange() method of List: the syntax and few working examples with output and detailed explanation for each example.