lastOrNull property

T? lastOrNull

The last element of this iterable, or null if the iterable is empty.

This computation may not be efficient. The last value is potentially found by iterating the entire iterable and temporarily storing every value. The process only iterates the iterable once. If iterating more than once is not a problem, it may be more efficient for some iterables to do:

var lastOrNull = iterable.isEmpty ? null : iterable.last;


T? get lastOrNull {
  if (this is EfficientLengthIterable) {
    if (isEmpty) return null;
    return last;
  var iterator = this.iterator;
  if (!iterator.moveNext()) return null;
  T result;
  do {
    result = iterator.current;
  } while (iterator.moveNext());
  return result;