Search code examples
flutterflutter-widget

display row in flutter if certain condition is true or false


there is a row of widgets in flutter, I want it to be visible on meeting certain condition, if the condition is true it should not be visible and if condition is false it should be visible

below is the code

Container(
      child: Row(
        children: <Widget>[
          // Button send image
         Text("Text1"),
         Text("Text2"),
         Text("Text3"),
         Text("Text4"),

        ],
      ),
      width: double.infinity,
      height: 50.0,
      decoration: BoxDecoration(border: Border(top: BorderSide(color: greyColor2, width: 0.5)), color: Colors.white),
    )

Conditions you can say for instance

int a==b

if true not visible , if false visible

How may I achieve it?


Solution

  • This is on the assumption that the whole widget will either be visible or not which is applicable for any row also.

    One way of doing it is embedding it within a Visibility widget the visible property of the widget takes a boolean value

    Visibility(
      visible: (a == b), // condition here
      child: Container(
      child: Row(
        children: <Widget>[
          // Button send image
         Text("Text1"),
         Text("Text2"),
         Text("Text3"),
         Text("Text4"),
    
        ],
      ),
      width: double.infinity,
      height: 50.0,
      decoration: BoxDecoration(border: Border(top: BorderSide(color: greyColor2, width: 0.5)), color: Colors.white),
    )
    )
    

    Another way is to use the expression/operator condition ? (run this part if true) : (run this part if false)

    a == b ? 
    Container(
      child: Row(
        children: <Widget>[
          // Button send image
         Text("Text1"),
         Text("Text2"),
         Text("Text3"),
         Text("Text4"),
    
        ],
      ),
      width: double.infinity,
      height: 50.0,
      decoration: BoxDecoration(border: Border(top: BorderSide(color: 
     greyColor2, width: 0.5)), color: Colors.white),
    ) : Container(), // you can also replace this with Null
    

    you can use Container() which is an empty widget or you can simply put a Null so that no widget will be placed