To slice the first N elements from a list in Dart, you can use the sublist method provided by the List class.
In this example,
numbers
with integer values.sublist
method on the list object numbers
to create a new list containing the first N elements.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int n = 3;
List<int> slicedNumbers = numbers.sublist(0, n);
print('Sliced list: \$slicedNumbers');
}
Sliced list: [1, 2, 3]
In this example,
words
with string values.sublist
method on the list object words
to create a new list containing the first N elements.void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
int n = 2;
List<String> slicedWords = words.sublist(0, n);
print('Sliced list: \$slicedWords');
}
Sliced list: [apple, banana]
In this tutorial, we learned How to Slice First N Elements from a List in Dart language with well detailed examples.