Translate dynamic string using AppLocalizations in flutter

Viewed 528

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.

1 Answers

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