To slice the last N elements from a list in Dart, you can use list slicing with negative indices.
In this example,
numbers
with integer values.numbers.sublist(numbers.length - n)
to slice the last N elements.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int n = 3;
List<int> slicedNumbers = numbers.sublist(numbers.length - n);
print('Sliced list: \$slicedNumbers');
}
Sliced list: [3, 4, 5]
In this example,
words
with string values.words.sublist(words.length - n)
to slice the last N elements.void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
int n = 2;
List<String> slicedWords = words.sublist(words.length - n);
print('Sliced list: \$slicedWords');
}
Sliced list: [date, elderberry]
In this tutorial, we learned How to Slice Last N Elements from a List in Dart language with well detailed examples.