How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

前端 未结 18 2147
再見小時候
再見小時候 2020-11-30 18:50

So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples):



        
18条回答
  •  臣服心动
    2020-11-30 19:41

    This is great article and conversation. I tried to use the ternary operator as described. But the code didn't work resulting in an error as mentioned.

    Column(children: [ condition? Text("True"): null,],);
    

    The ternary example above is miss leading. Dart will respond with an error that a null was returned instead of widget. You can't return null. The correct way will be to return a widget:

    Column(children: [ condition? Text("True"): Text("false"),],); 
    

    In order for the ternary to work you need to return a Widget. If you don't want to return anything you can return a empty container.

    Column(children: [ condition? Text("True"): Container(),],); 
    

    Good luck.

提交回复
热议问题