splitAfterIndexed method Null safety

Iterable<List<T>> splitAfterIndexed(
  1. bool test(
    1. int index,
    2. T element
    )
)

Splits the elements into chunks after some elements and indices.

Each element and index is checked using test for whether it should end the current chunk. If so, the elements since the previous chunk-ending element are emitted as a list. Any final elements are emitted at the end, whether the last element should be split after or not.

Example:

var parts = [1, 0, 2, 1, 5, 7, 6, 8, 9].splitAfterIndexed((i, v) => i < v);
print(parts); // ([1, 0], [2, 1], [5, 7, 6], [8, 9])

Implementation

Iterable<List<T>> splitAfterIndexed(
    bool Function(int index, T element) test) sync* {
  var index = 0;
  List<T>? chunk;
  for (var element in this) {
    (chunk ??= []).add(element);
    if (test(index++, element)) {
      yield chunk;
      chunk = null;
    }
  }
  if (chunk != null) yield chunk;
}