flutterperformancewidgetreactiveflutter-getx

GetX reactive bool listen with conditional widget adding


I have a reactive bool. Now if that is true I show a widget , but in case that is false then I don't need to show anything at all in that place.

As of now I am adding a Empty Container() or SizedBox.shrink() if the bool is false. Is there any way to not adding any Widget at all?

Example :

Obx(() {
  if (rxBool.value)) {
    return Positioned(
      right: 45.0,
      bottom: constraints.maxHeight / 4 + 85,
      child: GestureDetector(
        onTap: () => controller.toggleTooltip(),
        child: SomeWidgetIWantToShow(),
      ),
    );
  }
  return const SizedBox.shrink();
})

in this how can I avoid return const SizedBox.shrink(); when rxBool.value == false


Solution

  • If the widget is child of a parent that as several children, like a Column or Row you can easily insert if statements within the list of children. Like this for example

    Column(children: [
      SomeWidget(),
      SomeOtherWidget(),
      if (myBool) ConditionalWidget(),
      LastWidget(),
    ],)
    

    EDIT:
    If your code is something like this:

    Column(children: [
      SomeWidget(),
      SomeOtherWidget(),
      Obx((){
        if (rxBool.value) {
          return Positioned(
            right: 45.0,
            bottom: constraints.maxHeight / 4 + 85,
            child: GestureDetector(
              onTap: () => controller.toggleTooltip(),
              child: SomeWidgetIWantToShow(),
            ),
          );
        }
        return const SizedBox.shrink();
      }),
      LastWidget(),
    ],)
    

    you can make it this instead

      Obx(()=>
        Column(children: [
          SomeWidget(),
          SomeOtherWidget(),
          if (rxBool.value)  Positioned(
            right: 45.0,
            bottom: constraints.maxHeight / 4 + 85,
            child: GestureDetector(
              onTap: () => controller.toggleTooltip(),
              child: SomeWidgetIWantToShow(),
            ),
          ),
          LastWidget(),
        ],),
      )