dam034
dam034

Reputation: 411

How to add elements to a column if there is a condition in flutter?

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

Answers (1)

Christopher Moore
Christopher Moore

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

Related Questions