elementAtOrElseNullable method

E? elementAtOrElseNullable(
  1. int index,
  2. E? defaultValue(
    1. int index
    )
)

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

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

Implementation

E? elementAtOrElseNullable(int index, E? Function(int index) defaultValue) {
  if (index < 0) return defaultValue(index);
  var count = 0;
  for (var element in this) {
    if (index == count++) return element;
  }
  return defaultValue(index);
}