Flutter internationalization - Dynamic strings

为君一笑 提交于 2020-12-04 19:47:04

问题


I'm translating my app to spanish using the intl package.

locales.dart

class AppLocale {
...
   String get folder => Intl.message("Folder", name: 'folder');
...
}

messages_es.dart

class MessageLookup extends MessageLookupByLibrary {
      get localeName => 'es';

      final messages = _notInlinedMessages(_notInlinedMessages);
      static _notInlinedMessages(_) => <String, Function> {
            "folder": MessageLookupByLibrary.simpleMessage("Carpeta"),
      };
}

I call it using the following code:

AppLocale.of(context).folder

It is working fine.

However, I need to create "dynamic" strings. For example:

"Hi, {$name}"

Then I would call this string, passing this "name" as parameter, or something like this. It would be translate as "Hola, {$name}" in spanish.

It is possible using this intl package?


回答1:


The README of the intl package explains that example https://github.com/dart-lang/intl

The purpose of wrapping the message in a function is to allow it to have parameters which can be used in the result. The message string is allowed to use a restricted form of Dart string interpolation, where only the function's parameters can be used, and only in simple expressions. Local variables cannot be used, and neither can expressions with curly braces. Only the message string can have interpolation. The name, desc, args, and examples must be literals and not contain interpolations. Only the args parameter can refer to variables, and it should list exactly the function parameters. If you are passing numbers or dates and you want them formatted, you must do the formatting outside the function and pass the formatted string into the message.

greetingMessage(name) => Intl.message(
      "Hello $name!",
      name: "greetingMessage",
      args: [name],
      desc: "Greet the user as they first open the application",
      examples: const {'name': "Emily"});
  print(greetingMessage('Dan'));

Below this section there are more complex examples explained that also deal with plurals and genders.




回答2:


In order to use placeholders in your translations you need to:

  • Add that placeholder as a getter argument
  • Mention that placeholder with $ prefix in the translation (ie $name)
  • Add the placeholder in args list when calling Intl.message

So a full example looks like this:

greetingMessage(name) => Intl.message(
  "Hello $name!",
  name: 'greetingMessage',
  args: [name]
);


来源:https://stackoverflow.com/questions/52278035/flutter-internationalization-dynamic-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!