elementAtOrElse method

E elementAtOrElse(
  1. int index, {
  2. E orElse(
    1. int index
    )?,
})

Returns an element at the given index or the result of calling the orElse function if the index is out of bounds.

final list = [1, 2, 3, 4];
final first = list.elementAtOrElse(0); // 1
final fifth = list.elementAtOrElse(4, (_) => -1); // -1

Implementation

E elementAtOrElse(int index, {E Function(int index)? orElse}) {
  orElse ??= (_) => throw StateError("No element");

  if (index < 0) return orElse(index);

  final it = iterator;
  var skipCount = index;
  while (it.moveNext()) {
    if (0 == skipCount) return it.current;
    skipCount--;
  }

  return orElse(index);
}