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
.
Parameter | Optional/Required | Description |
---|---|---|
start | required | the starting index of the sublist |
end | optional | the ending index of the sublist (default is the length of the list) |
List.sublist() returns value of type List<E>
.
In this example,
numbers
.sublist()
method on numbers
with a start index of 1 and an end index of 4 (exclusive).numbers
.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
List<int> subNumbers = numbers.sublist(1, 4);
print(subNumbers);
}
[2, 3, 4]
In this example,
characters
.sublist()
method on characters
with a start index of 2 (inclusive) and no end index (defaulting to the length of the list).characters
.void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
List<String> subChars = characters.sublist(2);
print(subChars);
}
[c, d, e]
In this example,
fruits
.sublist()
method on fruits
with a start index of 1 and an end index of 4 (exclusive).fruits
.void main() {
List<String> fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
List<String> subFruits = fruits.sublist(1, 4);
print(subFruits);
}
[banana, cherry, date]
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.