Home > Mobile >  how can get radio value in Flutter?
how can get radio value in Flutter?

Time:04-05

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?

CodePudding user response:

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

CodePudding user response:

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);
  • Related