passing dynamic strings to AppLocalizations.of(context)! in Flutter

192

What you are trying to do, invoking a method by its name at runtime, is called reflection, and this is not supported by Flutter natively (though there are packages that try to emulate this, but I have no experience with them).

What will work for you, even though it might be tedious, is manually mapping your value from the API to the corresponding method from AppLocalizations.of(context).

String localizedString = getLocalizedString(snapshot.data![index].state_pickup[0], context);

String getLocalizedString(String key, BuildContext context) {
  switch (key) {
    case "possible_api_value_1":
      return AppLocalizations.of(context)!.possibleApiValue1;
    case "possible_api_value_2":
       return AppLocalizations.of(context)!.possibleApiValue2;
      ...
     }
Share:
192
Husam Alhwadi
Author by

Husam Alhwadi

21 years experience in Building software applications (backend and frontend)

Updated on December 01, 2022

Comments

  • Husam Alhwadi
    Husam Alhwadi over 1 year

    right now Im working in App using Flutter and I have 4 different languages, I use json (arb files) for localization (translation)

    I need to pass different string values which app fetch them using API's as shown in below example

    AppLocalizations.of(context)!snapshot.data![index].state_pickup[0]
    

    however "AppLocalizations.of(context)!" doesn't fetch the return data from snapshot.data![index].state_pickup[0] and instead it looks for its as string and tries to search for match string name in AppLocalization.dart class?

    Any idea how I can pass dynamic string arguments to AppLocalizations.of(context)!?

  • Husam Alhwadi
    Husam Alhwadi about 2 years
    Thank you,I have no other choice, hopes to find more practical solution since i have a lot of dynamic text which need to be translated into 4 languages!!