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

前端 未结 18 2130
再見小時候
再見小時候 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:30

    You can use ternary operator for conditional statements in dart, It's use is simple

    (condition) ? statement1 : statement2
    

    if the condition is true then the statement1 will be executed otherwise statement2.

    Taking a practical example

    Center(child: condition ? Widget1() : Widget2())
    

    Remember if you are going to use null as Widget2 it is better to use SizedBox.shrink() because some parent widgets will throw an exception after getting a null child.

提交回复
热议问题