Reputation: 411
I have this code:
Column(
children: [
MyFirstWidget(),
MySecondWidget(),
],
);
Now I want to add some widgets to that column if there is a condition. Here an example:
Column(
children: [
MyFirstWidget(),
MySecondWidget(),
if(condition == true) {
MyThirdWidget(),
MyFourthWidget(),
}
],
);
I know this code is wrong, but how can I do this is correct dart programming?
Upvotes: 3
Views: 2005
Reputation: 17133
In Dart 2.3, they added the collection if
and spread operators which you can use here to conditionally add these widgets.
The collection if
conditionally adds the list of third and fourth widgets and the spread operator concisely inserts these elements into the collection.
Column(
children: [
MyFirstWidget(),
MySecondWidget(),
if(condition == true)
...[MyThirdWidget(), MyFourthWidget()]
],
);
Additionally doing == true
is unnecessary. You can just do if(condition)
for slightly cleaner code:
Column(
children: [
MyFirstWidget(),
MySecondWidget(),
if(condition)
...[MyThirdWidget(), MyFourthWidget()]
],
);
These both will only show the third and fourth widgets when condition is true
.
Upvotes: 13