0
Follow
0
View

How to get the chosen data from a RadioButton in Flutter

wangshanglantian 注册会员
2023-01-25 03:38

You need to define function and variable in your main class like this:

var radioButtonResult = '';

void radioOnChange(String value){
   setState(() {
      radioButtonResult = value;
   });
}

then pass this function to your RadioButtonWidget like this:

RadioButtonWidget(radioOnChange: radioOnChange),

the change your RadioButtonWidget class to this to accept the function you pass:

class RadioButtonWidget extends StatefulWidget {
  final Function(String) radioOnChange;//< --- add this
  const RadioButtonWidget({Key? key, required this.radioOnChange}) : super(key: key);
 
  @override
  State createState() => _RadioButtonWidgetState();
}
 
class _RadioButtonWidgetState extends State {
 String colorRadioButton = "rosa";

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          const SizedBox(height: 30,),
          const Text('Elija el color de la tarea'),
          const SizedBox(height: 10,),
          ListTile(
            title: Text("Rosa"),
            tileColor: Color(0xFFFF66C4),
            leading: Radio(
              activeColor: Color(0xFFFF66C4),
              focusColor: Color(0xFFFF66C4),
              value: "rosa",
              groupValue: colorRadioButton, 
              onChanged: widget.radioOnChange,//< --- change this
            )
          ),
dw507003 注册会员
2023-01-25 03:38

You can create a callback method on RadioButtonWidget to get data on parent class.

class RadioButtonWidget extends StatefulWidget {
  final Function(String?) onRadioButtonChanged ;
  const RadioButtonWidget({Key? key, required this.onRadioButtonChanged}) : super(key: key);

  @override
  State createState() => _RadioButtonWidgetState();
}

And call it on onChanged

groupValue: colorRadioButton, 
onChanged: (value) {
  setState(() {
    colorRadioButton = value.toString();
  });
  widget.onRadioButtonChanged(value);
  
},

Now you can get value

 RadioButtonWidget( // dont use const
  onRadioButtonChanged: (value) {
    print(value);
  },
),

About the Author

Question Info

Publish Time
2023-01-25 03:38
Update Time
2023-01-25 03:38