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
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) |
Return Type
List.sublist() returns value of type List<E>
.
✐ Examples
1 Get sublist of numbers
In this example,
- We create a list of integers named
numbers
. - We then use the
sublist()
method onnumbers
with a start index of 1 and an end index of 4 (exclusive). - The resulting sublist contains elements at indexes 1, 2, and 3 from
numbers
. - 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,
- We create a list of characters named
characters
. - We then use the
sublist()
method oncharacters
with a start index of 2 (inclusive) and no end index (defaulting to the length of the list). - The resulting sublist contains elements starting from index 2 to the end of
characters
. - 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,
- We create a list of strings named
fruits
. - We then use the
sublist()
method onfruits
with a start index of 1 and an end index of 4 (exclusive). - The resulting sublist contains elements at indexes 1, 2, and 3 from
fruits
. - 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.