Dart Tutorials

Dart List sublist()
Syntax & Examples

Syntax of List.sublist()

The syntax of List.sublist() method is:

 List<E> sublist(int start, [int? end]) 

This sublist() method of List returns a new list containing the elements between start and end.

Parameters

ParameterOptional/RequiredDescription
startrequiredthe starting index of the sublist
endoptionalthe ending index of the sublist (default is the length of the list)

Return Type

List.sublist() returns value of type List<E>.



✐ Examples

1 Get sublist of numbers

In this example,

  1. We create a list of integers named numbers.
  2. We then use the sublist() method on numbers with a start index of 1 and an end index of 4 (exclusive).
  3. The resulting sublist contains elements at indexes 1, 2, and 3 from numbers.
  4. We print the sublist to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  List<int> subNumbers = numbers.sublist(1, 4);
  print(subNumbers);
}

Output

[2, 3, 4]

2 Get sublist of characters

In this example,

  1. We create a list of characters named characters.
  2. We then use the sublist() method on characters with a start index of 2 (inclusive) and no end index (defaulting to the length of the list).
  3. The resulting sublist contains elements starting from index 2 to the end of characters.
  4. We print the sublist to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd', 'e'];
  List<String> subChars = characters.sublist(2);
  print(subChars);
}

Output

[c, d, e]

3 Get sublist of strings

In this example,

  1. We create a list of strings named fruits.
  2. We then use the sublist() method on fruits with a start index of 1 and an end index of 4 (exclusive).
  3. The resulting sublist contains elements at indexes 1, 2, and 3 from fruits.
  4. We print the sublist to standard output.

Dart Program

void main() {
  List<String> fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
  List<String> subFruits = fruits.sublist(1, 4);
  print(subFruits);
}

Output

[banana, cherry, date]

Summary

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