1
votes

I worked with flutter for almost a year and since it wasn't production-ready for web development I needed to switch to react.

To render object conditionally inside my build method I had to put an if-else statement rendering my custom widget if the condition was met or a random empty container in the other case.

@override
Widget build(BuildContext context) {
 return Container(
   child: condition == true 
       ? new MyCustomWidget() 
       : new Container() //Random empty container to fill the else statement
 )
)

Even if this doesn't cause any rendering problem, it's still can be ambiguous for someone reading the code. After working with react I saw that it provides a way to display only the if block using the following notation:

<div>
  {condition == true && <MyCustomReactComponent/>} //this block is displayed only if the condition is met
</div>

I was guessing if flutter has a way to do something similar.

3

3 Answers

2
votes

I use Column in situations like these, you can declare multiple conditions depending upon which widget you want to display for which condition.

Column(
     children: <Widget>[
       if(your condition) CustomWidgetOne(),
       if(your condition) CustomWidgetTwo(),
       if(your condition) CustomWidgetThree(),
           
      ],
  ),
0
votes

It depends on which condition you want to display a specific widget.

For exemple, if you want to display a side bar widget only on wide webpages you can use the LayoutBuilder widget which you can use like @media on vanilla web.

Otherwise you'll need to use ternary operator as you did.

If you want a more complete answer you can check a talk that Mariano Zorrilla on the subject on the 28/01/21

0
votes

You can always return null, as if you're passing no child at all.