when
Applies a callback when a predicate holds, otherwise returns the value unchanged.
Lecture
when(predicate, callback, value) is a single conditional
expressed as data: if predicate(value) is true, the result
is callback(value); otherwise the result is value
itself, untouched. It reads nicely inside a map callback when
you want to transform only the elements that need it and leave the rest alone.
FxTS's version can widen the return type to a union T | R
when the branches disagree. Dart has no union types, so both the
callback branch and the pass-through branch must share the
same type T — if you need genuinely different result types,
reach for cases instead, which
allows R to differ from the input type.
Demo 1 · Basics
Demo 2 · Clamping values in a pipeline
Try it yourself
Exercise: use when to double only the positive prices,
leaving negative ones untouched.