'how can get radio value in Flutter?
how can get radio value in Flutter?
I writing this code and tring to get value, but has a little problems.
Code
enum SingingCharacter { Australia, USA }
SingingCharacter? _character = SingingCharacter.Australia;
String res = await AuthMethods().signUpUser(
email: _emailController.text,
password: _passwordController.text,
username: _usernameController.text,
bio: _bioController.text,
file: _image!,
country: _character.toString(),
);
Column(
children: <Widget>[
RadioListTile<SingingCharacter>(
title: const Text('Australia'),
value: SingingCharacter.Australia,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
RadioListTile<SingingCharacter>(
title: const Text('USA'),
value: SingingCharacter.USA,
groupValue: _character,
onChanged: (SingingCharacter? value) {
setState(() {
_character = value;
});
},
),
],
),
When the use register and choose the country, I will got this value SingingCharacter.Australia and writing firebase, but I hope I could got like this value Australia or USA, not got SingingCharacter.Australia or SingingCharacter.USA
Where is my falut code?
Solution 1:[1]
You have given the RadioListTile<T> where T as SingingCharacter. So you will get the value as SingingCharacter.USA or SingingCharacter.Australia. If you want only the name, try like below.
onChanged: (SingingCharacter? value) {
setState(() {
if (value != null) {
_character = value;
String enumValue = value.name; // USA
// or
enumValue = describeEnum(value); // USA
}
});
}
https://api.flutter.dev/flutter/foundation/describeEnum.html
Solution 2:[2]
For a flexible solution, perhaps you can leverage extension, something like this:
enum SingingCharacter { Australia, USA }
extension SingingCharacterExt on SingingCharacter {
String get code {
switch (this) {
case SingingCharacter.Australia:
return "AU";
case SingingCharacter.USA:
return "US";
}
}
}
Usage:
debugPrint(SingingCharacter.Australia.code);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Praveen G |
| Solution 2 | ישו ×והב ×ותך |
