In Dart / Flutter a Row widget can be written like this:
Row(
children: <Widget>[
Text('a'),
Text('b'),
],
)
How could that be changed if the second text should only be added if a condition is met? It could be:
bool condition = ...;
List<Widget> rowComponent = [Text('a')];
if(condition) {
rowComponent.add(Text('b'));
}
Row(
children: rowComponent,
);
Is there a more idiomatic and less verbose way? Something like:
bool condition = ...;
Row(
children: <Widget>[
Text('a'),
condition ? Text('b') : Container(),
],
)
This does work but only in the context of Flutter (where the Container can be used as a "void object") and creates this unused Container. Is there a better way?
Thanks!
What about this way? Maybe you like this one.
You don't need to use the Container()
bool condition = ...;
Row(
children: <Widget>[
if (condition) Text('c'),
],
)
Reference to this: prefer_if_elements_to_conditional_expressions
I do something like this:
bool notNull(Object o) => o != null;
bool condition = ...;
Row(
children: <Widget>[
Text('a'),
condition ? Text('b') : null,
].where(notNull).toList(),
)
This is also useful if you have a method that will either create and returna Widget, or return null.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.