list<T extends Object> static method

List<Widget> list<T extends Object>(
  1. T? value, {
  2. Widget? child(
    1. T
    )?,
  3. Iterable<Widget?> children(
    1. T
    )?,
  4. bool buildWhen(
    1. T value
    )?,
})

Creates a list of widgets based on a nullable value.

This method provides two ways to generate widgets:

  1. Using child to create a single widget
  2. Using children to create multiple widgets

Returns an empty list if value is null or if child returns null. When using children, null widgets are filtered out from the result.

  • value - The nullable value to check
  • child - Optional callback to create a single widget
  • children - Optional callback to create multiple widgets
  • buildWhen - Optional predicate; if provided and returns false, an empty list is returned even when value is non-null. When omitted the list is built purely based on nullability.

Example with single child:

MaybeWidget.list(
  maybeUser,
  child: (user) => Text(user.name),
)

Example with multiple children:

MaybeWidget.list(
  maybeUser,
  children: (user) => [
    Text(user.name),
    if (user.isAdmin) Icon(Icons.star),
  ],
)

Example using buildWhen:

// Only include widgets when the user is active.
MaybeWidget.list(
  maybeUser,
  child: (user) => Text(user.name),
  buildWhen: (user) => user.isActive,
);

Implementation

static List<Widget> list<T extends Object>(
  T? value, {
  Widget? Function(T)? child,
  Iterable<Widget?> Function(T)? children,
  bool Function(T value)? buildWhen,
}) {
  final maybeVal = _passes(value, buildWhen);
  if (maybeVal == null) return const [];
  if (children != null) return List.unmodifiable(children(maybeVal).nonNulls);
  final maybeChild = child?.call(maybeVal);

  return maybeChild == null ? const [] : [maybeChild];
}