Home > Software engineering >  How can i print checkbox value on Text() Widget using Flutter
How can i print checkbox value on Text() Widget using Flutter

Time:09-25

Is there a way to print checkbox value in a Text widget Eg. I make two checkbox which have a value of POD and Prepaid i would like to print out the selected checkbox value on Text() Widget.

Code:-

Padding(
  padding: const EdgeInsets.all(8.0),
  child: Row(
    children: [
      Checkbox(
        value: prepaidCheckBoxValue,
        shape: const CircleBorder(),
        checkColor: Colors.white,
        onChanged: (value) {
          prepaidCheckBoxValue = !prepaidCheckBoxValue;
          //print(prepaidCheckBoxValue);
          setState(() {});
        },
      ),
      const Text(
        'Prepaid',
        style: TextStyle(
          fontSize: 20.0,
        ),
      ),
      const SizedBox(
        width: 30.0,
      ),
      Checkbox(
        value: podCheckBoxValue,
        shape: const CircleBorder(),
        checkColor: Colors.white,
        onChanged: (value) {
          podCheckBoxValue = !podCheckBoxValue;
          setState(() {});
          //print(value);
        },
      ),
      const Text(
        'Pay on Delivery',
        style: TextStyle(
          fontSize: 20.0,
        ),
      ),
    ],
  ),
),

Image

CodePudding user response:

My recommendation

create a enum for payment methods

enum PaymentTypes {
  prepaid,
  pay_on_delivery,
}

create a local variable to store selected payment method in your state class

PaymentTypes selectedPaymentType;

set the selected payment method on checkbox onChange method

Checkbox(
//prepaid checkbox
...
        onChanged: (value) {
          podCheckBoxValue = !podCheckBoxValue;
          setState(() {
             selectedPaymentType = PaymentTypes.prepaid;
          });
          //print(value);
        },
      ),

Checkbox(
//pay on delivery checkbox
...
        onChanged: (value) {
          podCheckBoxValue = !podCheckBoxValue;
          setState(() {
             selectedPaymentType = PaymentTypes.pay_on_delivery;
          });
          //print(value);
        },
      ),

use selectedPaymentType value on Textbox

const Text(
 describeEnum(selectedPaymentType).replaceAll(RegExp('_'), ' ')
)

Or you can just use a string to store the checkbox value without enums

String selectedPaymentType;

      onChanged: (value) {
          podCheckBoxValue = !podCheckBoxValue;
          setState(() {
             selectedPaymentType = 'Pay on delivery';
          });
          //print(value);
        },
      ),

const Text(
 selectedPaymentType
)

  • Related