Dart Tutorials

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

ParameterOptional/RequiredDescription
startrequiredthe start index of the range to fill
endrequiredthe end index of the range to fill
fillValueoptionalthe 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,

  1. We create a list named numbers containing the numbers 1, 2, 3, 4, 5.
  2. We then use the fillRange() method to fill the range from index 1 to 3 with zeros.
  3. 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,

  1. We create a list named characters containing the characters 'a', 'b', 'c', 'd', 'e'.
  2. We then use the fillRange() method to fill the range from index 2 to 4 with the character 'x'.
  3. 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,

  1. We create a list named words containing the strings 'apple', 'banana', 'cherry', 'date', 'fig'.
  2. We then use the fillRange() method to fill the range from index 1 to 4 with the string 'orange'.
  3. 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.