3

I have a Radio and I want to disable it with a condition, like:

if (enabled == true){
*enable radio button*
} else {
*disable radio button*
}

EDIT

I'll add the complete code of my class because I only added a portion of it.

Here is the complete code:

import 'package:flutter/material.dart';

class RadioButton extends StatelessWidget {
  final String label;
  final int groupValue;
  final int value;
  final ValueChanged<int> onChanged;

  const RadioButton(
      {super.key,
      required this.label,
      required this.groupValue,
      required this.value,
      required this.onChanged});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Radio<int>(
                        groupValue: groupValue,
                        value: value,
                        onChanged: (int? newValue) {
                          onChanged(newValue!);
                        }),
                  ),
                  Text(label),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }
}
  • [Check this I think this will work for you](https://stackoverflow.com/a/65559906/14216705) – Anas Rasheed Dec 21 '22 at 17:21
  • I tried your approach and have this error "The argument type 'void Function(int)?' can't be assigned to the parameter type 'void Function(int)'". Also I edited my code so you can see the complete class. – Eder Savillon Dec 21 '22 at 18:03

1 Answers1

3

To disable a Radio button, set onChanged to null:

return Radio(
      value: 1,
      groupValue: 1,
      onChanged: null,
    );
    

Edit: To disable it based on a condition:

var isDisabled = true;
    Radio(
      value: 1,
      groupValue: 1,
      onChanged: isDisabled ? null : (value) {},
      

From the documentation on onChanged:

If null, the radio button will be displayed as disabled.


You can keep this trick of setting null in mind as it also disables other Icons/widgets.

MendelG
  • 14,885
  • 4
  • 25
  • 52