takeIf method

T? takeIf(
  1. bool predicate(
    1. T
    )
)

Returns this object if it satisfies predicate, or null otherwise.

Useful for concise conditional assignment and nullable chaining:

final name = potentialName.takeIf((it) => it.isNotEmpty);
final positiveNumber = someNullableInt?.takeIf((it) => it > 0);

Implementation

T? takeIf(bool Function(T) predicate) {
  return predicate(this) ? this : null;
}