简体   繁体   中英

How to get Radio button value in Flutter

I am using below code for the gender selection in a flutter application. In this, this is working fine, but I am not able to retrieve the value of gender in Text format. How should I do that?

final gender = Padding(
      padding: EdgeInsets.only(top: 0.0),
      child: Row(
        children: <Widget>[
          Radio(
            value: 0,
            groupValue: _genderRadioBtnVal,
            onChanged: _handleGenderChange,
          ),
          Text("Male"),
          Radio(
            value: 1,
            groupValue: _genderRadioBtnVal,
            onChanged: _handleGenderChange,
          ),
          Text("Female"),
          Radio(
            value: 2,
            groupValue: _genderRadioBtnVal,
            onChanged: _handleGenderChange,
          ),
          Text("Other"),
        ],
      ),
    );

void _handleGenderChange(int value) {
    setState(() {
      _genderRadioBtnVal = value;
    });
  }

Since you are using the values as 0,1,2 you get that in onChanged.If you want String values like "Male", "Female" and "other" you can change your value to String type and give them appropriate values.

Row(
    children: <Widget>[
      Radio<String>(
        value: "Male",
        groupValue: _genderRadioBtnVal,
        onChanged: _handleGenderChange,
      ),
      Text("Male"),
      Radio<String>(
        value: "Female",
        groupValue: _genderRadioBtnVal,
        onChanged: _handleGenderChange,
      ),
      Text("Female"),
      Radio<String>(
        value: "Other",
        groupValue: _genderRadioBtnVal,
        onChanged: _handleGenderChange,
      ),
      Text("Other"),
    ],
  );

void _handleGenderChange(String value) {
  setState(() {
    _genderRadioBtnVal = value;
  });
}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM