Dart Tutorials

Dart List getRange()
Syntax & Examples

Syntax of List.getRange()

The syntax of List.getRange() method is:

 Iterable<E> getRange(int start, int end) 

This getRange() method of List creates an Iterable that iterates over a range of elements.

Parameters

ParameterOptional/RequiredDescription
startrequiredthe starting index of the range
endrequiredthe ending index of the range (exclusive)

Return Type

List.getRange() returns value of type Iterable<E>.



✐ Examples

1 Get range of numbers from a list

In this example,

  1. We create a list numbers containing integers 1 to 5.
  2. We then get a range from index 1 (inclusive) to index 4 (exclusive) using getRange().
  3. The resulting range is [2, 3, 4] which is printed after converting it to a list.

Dart Program

void main() {
  var numbers = [1, 2, 3, 4, 5];
  var range = numbers.getRange(1, 4);
  print(range.toList());
}

Output

[2, 3, 4]

2 Get range of characters from a list

In this example,

  1. We create a list characters containing characters 'a' to 'e'.
  2. We then get a range from index 2 (inclusive) to index 5 (exclusive) using getRange().
  3. The resulting range is ['c', 'd', 'e'] which is printed after converting it to a list.

Dart Program

void main() {
  var characters = ['a', 'b', 'c', 'd', 'e'];
  var range = characters.getRange(2, 5);
  print(range.toList());
}

Output

[c, d, e]

3 Get range of words from a list

In this example,

  1. We create a list words containing words 'apple' to 'eggplant'.
  2. We then get a range from index 0 (inclusive) to index 3 (exclusive) using getRange().
  3. The resulting range is ['apple', 'banana', 'cherry'] which is printed after converting it to a list.

Dart Program

void main() {
  var words = ['apple', 'banana', 'cherry', 'date', 'eggplant'];
  var range = words.getRange(0, 3);
  print(range.toList());
}

Output

[apple, banana, cherry]

Summary

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