Home > Software engineering >  Conditionally hide and show Widget
Conditionally hide and show Widget

Time:08-11

I am completely new to flutter started learning some time ago. I want to conditionally hide and show the following widget (SdCardHeadlineLeft) based on a condition which is paymentType = cash and order type = delivery based on these two conditions I want to hide it and if the condition is paymentType = isApiCheckout I want to show this widget.

I tried the Visibility widget but the problem with that is it completely hides the widget, but I want to do it on the condition

Hide: paymentType = cash, orderType = delivery

Show: paymentType = isApiCheckout

class _TippingComponentState extends State<TippingComponent> {
@override
Widget build(BuildContext context) {
return SdCardHeadlineLeft(
    cardHeadline: AppLocalizations.of(context)!.labelWouldYouLikeToTip,
    isExpandable: true,
    extraLineBeforeExpanded: false,
    hasButtonRight: false,
    headlineLeftBodyCard: 
    Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Observer(
        builder: (_) => Column(
          children: [
            _CashOrBillWidget(
              pickedCashOrBill: widget.pickedCashOrBill,
              onTipChanged: widget.onTipChanged,
            ),
            SdDividerNoPadding(positionTop: 1.0),
            if (widget.pickedCashOrBill == CashOrBill.tipOnBill)
              const TippingAmountComponent(),
          ],
        ),
      ),
    )
    );
  }
 }

CodePudding user response:

There is a widget called "Visibility" which can be used in the following manner:

Visibility(
  visible:paymentType == isApiCheckout,
  child:SdCardHeadlineLeft(...),
  replacement:SizedBox(), 
);

So basically it takes in a bool and if it's true, it will return 'child', if false, the 'replacement' will be returned.

CodePudding user response:

You can perform a simple condition check and return a sizedbox.shrink if its not met

return paymentType == isApiCheckout?SdCardHeadlineLeft(
    cardHeadline: AppLocalizations.of(context)!.labelWouldYouLikeToTip,
    isExpandable: true,
    extraLineBeforeExpanded: false,
    hasButtonRight: false,
    headlineLeftBodyCard: 
    Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Observer(
        builder: (_) => Column(
          children: [
            _CashOrBillWidget(
              pickedCashOrBill: widget.pickedCashOrBill,
              onTipChanged: widget.onTipChanged,
            ),
            SdDividerNoPadding(positionTop: 1.0),
            if (widget.pickedCashOrBill == CashOrBill.tipOnBill)
              const TippingAmountComponent(),
          ],
        ),
      ),
    )
    ): Sizedbox.shrink();

CodePudding user response:

try

return  paymentType == cash &&  type = deliver? SdCardHeadlineLeft(...) : Text("you can have others widget");

Or

 if(paymentType == isApiCheckout) 
   return SdCardHeadlineLeft(...);

 else return  SizedBox();
  • Related