Dart  Iterable  subList().

Dart Iterable subList().

subList()

  • A sublist method is used to return a new list containing a portion of an existing list. The portion of the list is defined by two arguments: the starting index and the ending index.
List<T> sublist<T>(List<T> list, int start, [int? end]) {
  // ignore: prefer_conditional_assignment
  if (end == null) {
    end = list.length;
  }

  if (start < 0 || start >= list.length || end < 0 || end > list.length || start > end) {
    throw ArgumentError('Invalid start or end index');
  }

  return list.sublist(start, end);
}

void main() {
  List<int> originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  // Getting sublist from index 2 to 5
  List<int> sub = sublist(originalList, 2, 8);

  print(sub); // Output: [3, 4, 5, 6]
}

Output

[3, 4, 5, 6, 7, 8]

Exited.