take method

List<T> take(
  1. int n
)

Returns a list containing the first n elements.

Example:

Iterable<int>? numbers = [1, 2, 3, 4, 5];
List<int> result = numbers.take(3);  // [1, 2, 3]

Implementation

List<T> take(int n) {
  if (this == null) return <T>[];
  if (n <= 0) return [];

  var list = <T>[];
  if (this is Iterable) {
    if (n >= this!.length) return this!.toList();

    var count = 0;
    var thisList = this!.toList();
    for (var item in thisList) {
      list.add(item);
      if (++count == n) break;
    }
  }
  return list;
}