windowed method

Iterable<List<T>> windowed(
  1. int size
)

Returns a sliding window view of size over this iterable.

Each window is a list of size consecutive elements. Fewer windows than elements are returned (e.g. for n elements, n - size + 1 windows).

[1, 2, 3, 4].windowed(2);  // [[1, 2], [2, 3], [3, 4]]
[1, 2, 3].windowed(4);     // [] (size exceeds length)

Implementation

Iterable<List<T>> windowed(int size) sync* {
  if (size <= 0) throw ArgumentError.value(size, 'size', 'must be positive');
  final list = toList();
  if (list.length < size) return;
  for (var i = 0; i <= list.length - size; i++) {
    yield list.sublist(i, i + size);
  }
}