orNull<W extends Widget, T extends Object> static method
- T? value,
- W? builder(
- T
- bool buildWhen(
- 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 returnsnull(allowing you to naturally skip the widget in list literals without extraifchecks).- non-
null- the optionalbuilderis invoked and its result returned. Ifbuilderitself is omitted or returnsnull, the overall result is alsonull.
Generics:
Trepresents the (non-null) value type expected bybuilder.Wrepresents the widget subtype you expect thebuilderto return. By default the compiler will usually inferWfor 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 returnsfalsethe method returnsnulleven ifvalueis non-null. When omitted only the null-check onvalueis 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);
}