How to show/hide widgets programmatically in Flutter

Definition:

Invisible: The widget takes up physical space on the screen but is not visible to user. This can be achieved using Visibility widget.

Gone: The widget doesn’t take up any physical space and is completely gone. This can be achieved using Visibility, if or if-else condition.

Invisible example:

Visibility(
  child: Text("Invisible"),
  maintainSize: true, 
  maintainAnimation: true,
  maintainState: true,
  visible: false, 
),

Gone example:

Visibility(
  child: Text("Gone"),
  visible: false,
),

Using if:

  • For one child:

    Column(
      children: <Widget>[
        Text('Good Morning'), // Always visible
        if (wishOnePerson) Text(' Mr ABC'), // Only visible if condition is true
      ],
    ) 
    
  • For multiple children:

    Column(
      children: [
        Text('Good Morning'), // Always visible
        if (wishAll) ... [ // These children are only visible if condition is true
          Text('Mr ABC'),
          Text('Mr DEF'),
          Text('Mr XYZ'),
        ],
      ],
    )
    

Using if-else:

  • For one child:

    Column(
      children: <Widget>[
        // Only one of them is visible based on 'isMorning' condition
        if (isMorning) Text('Good Morning')
        else Text ('Good Evening'),
      ],
    ) 
    
  • For multiple children:

    Column(
      children: [
        // Only one of the children will be shown based on `beforeSunset` condition
        if (beforeSunset) ... [
          Text('Good morning'),
          Text('Good afternoon'),
        ] else ... [
          Text('Good evening'),
          Text('Good night'),
        ],
      ],
    )
    

Leave a Comment