orNull<W extends Widget, T extends Object> static method

W? orNull<W extends Widget, T extends Object>(
  1. T? value,
  2. W? builder(
    1. T
    )?, {
  3. bool buildWhen(
    1. T value
    )?,
})

Conditional widget builder that returns null when value is null.

This lightweight utility mirrors the ergonomics of the main MaybeWidget widget for the specific scenario where you only need a nullable widget result (e.g. for nullable child: inputs, or inside a Flex/Stack/etc. children list, or in a collection literal with spread / if expressions) instead of inserting an always-present placeholder like SizedBox.shrink.

When the provided value is:

  • null - the method returns null (allowing you to naturally skip the widget in list literals without extra if checks).
  • non-null - the optional builder is invoked and its result returned. If builder itself is omitted or returns null, the overall result is also null.

Generics:

  • T represents the (non-null) value type expected by builder.
  • W represents the widget subtype you expect the builder to return. By default the compiler will usually infer W for you (e.g. Widget, Text, Icon, etc.).

Use cases include concise, allocation-free conditional widget inclusion:

Column(
  children: [
    const Text('Header'),
    ?MaybeWidget.orNull(subtitle, Text.new), // Add a subtitle if exists.
  ],
);

Simple example with inference:

final trailing = MaybeWidget.orNull<Text, DateTime>(
  lastEdited,
  (dt) => Text(timeAgo(dt)),
);

If you do not need a specialized widget subtype you can omit the generic arguments entirely and let inference work:

final maybeChip = MaybeWidget.orNull(tag, (t) => Chip(label: Text(t)));

Returns null when value is null or when builder is null.

  • buildWhen - Optional predicate; if provided and returns false the method returns null even if value is non-null. When omitted only the null-check on value is applied.

Example:

final subtitle = MaybeWidget.orNull<Text, String>(
  maybeSubtitle,
  Text.new,
  buildWhen: (s) => s.trim().isNotEmpty,
);

See also: MaybeWidget: the widget counterpart when you need a concrete fallback placeholder in the tree.

Implementation

static W? orNull<W extends Widget, T extends Object>(
  T? value,
  W? Function(T)? builder, {
  bool Function(T value)? buildWhen,
}) {
  final maybeValue = _passes(value, buildWhen);

  return maybeValue == null ? null : builder?.call(maybeValue);
}