How to conditionally add widgets to a list?
The new Dart syntax allows 'if' in lists, which leads to this simple solution:
Row(
children: <Widget>[
if (foo == 42) Text("foo"),
],
);
Row(
children: [
if (_id == 0) ...[
Container()
] else if(_id == 1)...[
Text("Hello")
] else ...[
SizedBox(width: 20)
],
],
),
Here's a simpler version I use:
Row(
children: [
Text("always included"),
skipNulls([
icon,
label,
]),
],
);
skipNulls<T>(List<T> items) {
return items..removeWhere((item) => item == null);
}
EDIT:
Since Dart 2.2, new syntaxes supports this natively:
Column(
children: [
if (foo != null) Text(foo),
Bar(),
],
);
This problem is currently debated on github here.
But for now, you can use dart sync*
functions:
Row(
children: toList(() sync* {
if (foo == 42) {
yield Text("foo");
}
}),
);
where toList
is:
typedef Iterable<T> IterableCallback<T>();
List<T> toList<T>(IterableCallback<T> cb) {
return List.unmodifiable(cb());
}
Not only it solves the conditional addition problem; it also allows for a "spread operator" thanks to yield*
. Example:
List<Widget> foo;
Row(
children: toList(() sync* {
yield Text("Hello World");
yield* foo;
}),
);