mapNotNull<U> method

  1. @useResult
Iterable<U> mapNotNull<U>(
  1. U? selector(
    1. T element
    )
)

Applies selector to each element and yields only the non-null results.

Replaces the common .map(...).whereType<U>() / .map(...).where((e) => e != null).cast<U>() two-step, which allocates an intermediate iterable of nullables and forces a cast. Doing both in one pass means selector runs exactly once per element and the result type is already the non-nullable U — no cast and no late null surprises.

Lazy: nothing runs until the result is iterated.

Example:

['1', 'x', '3'].mapNotNull(int.tryParse); // (1, 3)

Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
Iterable<U> mapNotNull<U>(U? Function(T element) selector) sync* {
  for (final T element in this) {
    final U? mapped = selector(element);
    if (mapped != null) {
      yield mapped;
    }
  }
}