Home > OS >  Showing only one of several widgets in Flutter
Showing only one of several widgets in Flutter

Time:02-05

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.

CodePudding user response:

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)

CodePudding user response:

To simply solve that, you can use a ternary operator with a widget like a container (or any that has a single child):

Container(
  child: condition == true 
    ? Text("Widget 1") 
    : Text("Widget 2")
)
  • Related