Translate dynamic string using AppLocalizations in flutter

253

You'll need to match you Gender enum value with your Map key for your Translations:

enum Gender { male, female }

void main() {
  final Map<String, String> translations = {
    "male": "مرد",
    "female": "زن",
  };

  Gender.values.map((gender) {
    final item = translations
      .entries
      .firstWhere((element) => element.key == gender.name);
    print(item.value);
  }).toList();
}

prints out:

مرد
زن

This is the full example scope with my logic:

Map Dart

Following your code, you'll need to find the matching key from the available localizations:

enum Gender { male, female }

final localization = AppLocalizations.of(context)!;

final genders = {
  "male": localization.male,
  "female": localization.female,
};

Gender.values.map((item) => DropdownMenuItem<Gender>(
       value: item,
       child: Text(genders.entries
           .firstWhere((entry) => entry.key == item.name)
           .value))
   .toList());
Share:
253
AmirSina Mashayekh
Author by

AmirSina Mashayekh

Computer engineering Bachelor's degree student in Babol Noshirvani University of Technology. Especially interested in embedded systems and microcontrollers (AVR &amp; PIC).

Updated on January 03, 2023

Comments

  • AmirSina Mashayekh
    AmirSina Mashayekh over 1 year

    I want to create a drop down menu for gender.

    enum Gender {
      male,
      female,
    }
    
    final localization = AppLocalizations.of(context)!;
    
    DropdownButtonFormField(
      hint: Text(localization.gender),
      items: Gender.values
          .map((item) => DropdownMenuItem<Gender>(
                value: item,
                // TODO: translate
                child: Text(item.name),
              ))
          .toList(),
    ),
    

    app_fa.arb:

    {
      "gender": "جنسیت",
      "male": "مرد",
      "female": "زن"
    }
    

    Everything works well, just I don't know how should I translate 'male' and 'female' and put them in menu items. I need a method which translates a string using keys in .arb file.

    I'm using flutter_localizations and main language of my app is Persian.

  • AmirSina Mashayekh
    AmirSina Mashayekh about 2 years
    this is good but if I modify the enum, I should modify genders too. Isn't there any way to use a string to get translation from arb file?
  • Mariano Zorrilla
    Mariano Zorrilla about 2 years
    you need to match both keys... if not, there's no way for you to map the enum with your localizations. If not, just use DropdownMenuItem<String> and use a map flike the one I created "genders"
  • Mariano Zorrilla
    Mariano Zorrilla about 2 years
    localization can only give you a value... but the value always change depending the language, that's why you need to create a key for those.
  • Hassan Kanso
    Hassan Kanso about 2 years
    it's a workaround, and it will lead to a boilerplate