Search code examples
fluttertabsvisibilityhidden

Showing only one of several widgets in Flutter


I have a space where I to show either widget1 or widget2 (and never both). How?

In fact, widget1 to contain a simple case of retrieved information and a button to switch to show widget2 (with more information) instead.

The only solution that I came up is to use Column(children: [widget1, widget2]) and tweak visibility of both widgets, but that's ugly. For example, there is no indication what is better Column or Row.


Solution

  • To do this, you have multiple options:

    (1) You can use conditional spread operator inside a column/widget

    Column(
     children: [
       if (yourCondition == true) ...[
          const Text("Widget 1")
       ] else ...[
          const Text("Widget 2")
       ],
     ],
    ),
    

    (2) You can use ternary operator inside a column/widget

    Column(
      children: [
        yourCondition == true
          ? const Text("Widget 1")
          : const Text("Widget 2"),
       ],
    ),
    

    (3) You can use Visibility widget inside a column/widget

    Column(
      children: [
        Visibility(
          visible: yourCondition == true,
          child: const Text("Widget 1"),
        ),
        Visibility(
          visible: yourCondition == false,
          child: const Text("Widget 2"),
        ),
      ],
    ),
    
    • For better code readability, use ternary operator if you have only one condition or non-nested conditions
    • For better code readability, use conditional spread operator if you have multiple conditions or nested conditions
    • Otherwise use Visibility widget (bur not recommended)