Flutter internationalization - Dynamic strings

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.


If you follow the official internationalization docs and specify all your phrases in .arb files, you can do parameters like this:

{
    "greeting": "Hi, {name}!",
    "@greeting": {
        "description": "Greet the user by their name.",
        "placeholders": {
            "name": {
                "type": "String",
                "example": "Jane"
            }
        }
    }
}

When you compile your code, a function like the following will be generated for you, complete with a nice docbloc to power your IDE tooltips:

  /// Greet the user by their name.
  ///
  /// In en, this message translates to:
  /// **'Hi, {name}!'**
  String greeting(String name);

So you can just use it like this:

Text(AppLocalizations.of(context)!.greeting("Koos"))