slice method
Creates a slice of a list from start up to, but not including, end.
This extension method works on iterables and returns a slice of the list.
If start is negative, it is treated as length + start where length is the length of the list.
If end is negative, it is treated as length + end.
Parameters:
- start (int): The start position.
- end (int): The end position, defaults to -1, indicating the end of the list.
Returns: List
Throws:
- RangeError: If
startorendis out of the bounds of the list length.
Example:
List<int> numbers = [1, 2, 3, 4, 5];
var sliced = numbers.slice(1, 3); // Returns [2, 3, 4]
Implementation
List<T> slice(int start, [int end = -1]) {
var list = this is List ? this as List<T> : toList();
if (start < 0) {
start = start + list.length;
}
if (end < 0) {
end = end + list.length;
}
RangeError.checkValidRange(start, end, list.length);
return list.sublist(start, end + 1);
}