简体   繁体   中英

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?

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

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

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