将动态字符串传递给Applocalization.of(上下文)!在颤抖中

发布于 2025-01-23 15:40:57 字数 463 浏览 2 评论 0原文

目前,我使用Flutter在应用程序中工作,并且我有4种不同的语言,我使用JSON(ARB文件)进行本地化(翻译),

我需要传递不同的字符串值,这些字符串值使用API​​使用API​​,如下所示,

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

但是> ” applocalizations.of(context)!“不会从snapshot.data![index] .State_pickup [0]中获取返回数据,而是将其作为字符串寻找并尝试到在plassacalization.dart类中搜索匹配字符串名称?

有什么想法我如何将动态字符串参数传递到applocalizations.of(context)!

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 example below

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 it 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)!?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

故事灯 2025-01-30 15:40:57

您正在尝试做的事情,在运行时用名称调用方法称为反射,这不是flutter flutter nentily 的支持(尽管有些软件包试图模仿这一点,但我对它们没有经验)。

即使可能很乏味,对您有用的是手动将您的值从API手动映射到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;
      ...
     }

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;
      ...
     }
飘然心甜 2025-01-30 15:40:57

另一种选择是使用(滥用?)ICU 选择选项。

这相当于翻译文件本身中的开关案例语句,而不是按照@pdurasie的描述进行编码。

如本地文档(在这里和< a href =“ https://localizely.com/i18n-questions/flutter/how-to-to-get-get-a-localization-message-with-a-a-a-dynamic-string-key-key-value-value-in-falue-in-flutter/” rel =” noreferrer“>在这里)

选择语句采用匹配的表格传递的变量或默认值为其他形式,这是所需的。

{
  "selectExample": "Today is {gender, select, male {his} female {her} other {their} } birthday"
  "@selectExample": {
    "placeholders": {
      "gender": {}
    }
  }
}

如果我们将价值男性的性别变量传递给示例,它将打印“今天是他的生日”。

海报的乱颤音代码看起来像:

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

尚不清楚选择选项的数量是否有任何限制。 ( icu ref docs

An alternative is to use (abuse?) the ICU Select option.

This is the equivalent of a switch case statement in the translation file itself, rather than coding it as described by @pdurasie.

As described in the Localizely documentation (here and here)

Select statements take the form that matches passed variable or defaults to other form, which is required.

{
  "selectExample": "Today is {gender, select, male {his} female {her} other {their} } birthday"
  "@selectExample": {
    "placeholders": {
      "gender": {}
    }
  }
}

If we pass gender variable with the value male to the example, it will print "Today is his birthday".

The Flutter code for the poster would look like:

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

It's unclear if there are any limits on the number of select options. (ICU ref docs)

半城柳色半声笛 2025-01-30 15:40:57

我面临类似的情况,需要动态翻译键,并在 loflow noreferrer“> l10n_mapper_generator 上解决这个问题。

由于Flutter不支持反射(但是DART确实),该解决方案试图通过使用指定的设置配置选项(您可以在Pub文档中找到)来生成本地化部分文件来模拟此问题。
这支持解析动态翻译键并定义其他有用的扩展方法。

示例设置

  • 安装L10N_MAPPER_ANNOTATION和L10N_MAPPER_GENERATOR软件包(在Pubspec.yaml中)

  • 安装ASSTAMN L10N_MAPPER_GENERATOR作为全局依赖关系dart dart pub dart pub lobalate l10n_mapper_generator_generator(在ermp>中需要)

  • 设置配置选项(在Pub文档中找到示例)

    >

  • 连续运行以下脚本

    • 生成与本地化相关的文件运行:
      flutter gen-l10n

    • 注释app_localizations要生成app_localizations.g.dart file>文件运行:
      DART PUB运行L10N_MAPPER_GENERATOR- gen-mapper

示例用法
由于生成的零件文件由键值对返回翻译键值组成,下面说明了用法

final applicationName = context.l10nParser('application_name'); // Localization mapper
final depositTimeFrame = context.l10nParser('deposit_timeframe'); // Instant

// parsing placeholder parameters
final convertBeforeWithdraw = context.l10nParser('convert_before_withdraw', arguments: ['CAD', 'EUR']); // * For withdrawing your CAD you first need to convert it back to EUR

I faced similar situation requiring dynamic translation keys parsed to AppLocalizations and created l10n_mapper_generator package to address this.

As flutter does not support reflection (but dart does) the solution tries to emulated this by generating localization part file using specified setup configuration options (which you can find in the pub documentation).
This supports parsing dynamic translation keys and defines other helpful extension methods.

Example setup

  • Install l10n_mapper_annotation and l10n_mapper_generator packages (in pubspec.yaml)

  • Install l10n_mapper_generator as global dependency dart pub global activate l10n_mapper_generator (required to run in terminal)

  • Setup configuration options (find example in pub documentation)

  • Run the below scrips in succession

    • generate localization-related files run:
      flutter gen-l10n

    • annotate app_localizations to generate app_localizations.g.dart file run:
      dart pub run l10n_mapper_generator --gen-mapper

Example usage
As the generated part file consists of key-value pair returning translation keys values, below illustrates usage

final applicationName = context.l10nParser('application_name'); // Localization mapper
final depositTimeFrame = context.l10nParser('deposit_timeframe'); // Instant

// parsing placeholder parameters
final convertBeforeWithdraw = context.l10nParser('convert_before_withdraw', arguments: ['CAD', 'EUR']); // * For withdrawing your CAD you first need to convert it back to EUR
风透绣罗衣 2025-01-30 15:40:57

我也遇到了这个问题并这样解决了它:

class DynamicLocalization {
  static String? arbContent;
  static Map<String, dynamic>? localizedMap = {};

  static init(Locale? locale) async {
    var filePath = 'lib/l10n/app_${locale?.languageCode ?? 'en'}.arb';
    arbContent = await rootBundle.loadString(filePath);
    localizedMap = jsonDecode(arbContent!) as Map<String, dynamic>;
  }

  static String translate(String key) {
    return localizedMap?[key] ?? key;
  }
}

然后使用它,

Text(DynamicLocalization.translate("dynamicKey"))

在使用此步骤之前,我也可以使用此步骤

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static Locale? appLocale = const Locale('tr');

  @override
  void initState() {
    DynamicLocalization.init(appLocale); //here when app initializing
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      locale: appLocale,
    );
  }
}

但是 DynamiClocalization 更改语言时:

setLocale(BuildContext context, Locale newLocale) {
    DynamicLocalization.init(newLocale);
    ...your locale changing logic
    }

3rd:将您的本地化文件添加到pubspec.yaml文件中的资产中:

assets:
    - lib/l10n/app_en.arb
    - lib/l10n/app_ru.arb
    - lib/l10n/app_tr.arb

说明:init功能将加载<函数。代码> .arb 文件作为映射。 Translate功能将尝试从该地图返回密钥的值。为什么我制作init函数的原因是,如果您尝试在翻译功能中获取所选.arb文件的内容,则它将返回future&lt; string&gt;text小部件中很难使用。

希望会有所帮助

I also had that problem and solved it like this:

class DynamicLocalization {
  static String? arbContent;
  static Map<String, dynamic>? localizedMap = {};

  static init(Locale? locale) async {
    var filePath = 'lib/l10n/app_${locale?.languageCode ?? 'en'}.arb';
    arbContent = await rootBundle.loadString(filePath);
    localizedMap = jsonDecode(arbContent!) as Map<String, dynamic>;
  }

  static String translate(String key) {
    return localizedMap?[key] ?? key;
  }
}

and using it like

Text(DynamicLocalization.translate("dynamicKey"))

but before using need to do this steps

1st: init DynamicLocalization when you give initial locale to your material app:

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static Locale? appLocale = const Locale('tr');

  @override
  void initState() {
    DynamicLocalization.init(appLocale); //here when app initializing
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      locale: appLocale,
    );
  }
}

2nd: init DynamicLocalization when you change your language:

setLocale(BuildContext context, Locale newLocale) {
    DynamicLocalization.init(newLocale);
    ...your locale changing logic
    }

3rd: add your localization files to assets inside pubspec.yaml file:

assets:
    - lib/l10n/app_en.arb
    - lib/l10n/app_ru.arb
    - lib/l10n/app_tr.arb

explanation: init function will load the content of your .arb file as Map. translate function will try to return your key's value from that map. The cause why I made a init function is if you trying get content of selected .arb file inside translate function then it will return Future<String> which will be difficult to use inside Text widgets.

hope will help

叹沉浮 2025-01-30 15:40:57

使用flutter easy_localization软件包,您可以在JSON翻译文件中使用Curly Braces'{}'来处理动态字符串表达式。以下是扑打代码和JSON文件的格式:

en_US.json:
{"before_notification": "Notifications will be set to {} minutes ago."}

 Flutter:
Text(tr('before_notification', args:[_selectedMinutes.round()]),), 

在此设置中,您在JSON文件中定义了带有Curly Braces'{}'的翻译密钥,作为动态值的占位符。然后,在绘制的代码中,您使用tr()函数访问翻译,然后使用ARGS参数将动态值传递给占位符。

通过遵循此结构,easy_localization软件包将在您的翻译中替换占位符{},并在运行时使用相应的动态值。这样,您可以根据所选语言轻松地显示带有动态内容的翻译字符串。

Using the Flutter easy_localization package, you can use curly braces '{}' in your JSON translation files to handle dynamic string expressions. Below is the format for the Flutter code and the JSON file:

en_US.json:
{"before_notification": "Notifications will be set to {} minutes ago."}

 Flutter:
Text(tr('before_notification', args:[_selectedMinutes.round()]),), 

In this setup, you define your translation key in the JSON file with curly braces '{}' as a placeholder for dynamic values. Then, in your Flutter code, you use the tr() function to access the translation, and you pass the dynamic value to the placeholder using the args parameter.

By following this structure, the easy_localization package will replace the placeholder {} in your translation with the corresponding dynamic value at runtime. This way, you can easily display translated strings with dynamic content based on the selected language.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文