Search code examples
fluttershow-hide

Conditionally hide and show Widget


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(),
          ],
        ),
      ),
    )
    );
  }
 }

Solution

  • 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();