Formatted Print on Dart/Flutter
Imagine your app become famous at world-wide level, where every person on the earth cannot live without it. Multiple countries’ representatives approaching you either by land, sea, or air, aiming for future investment. They all are asking for your app to be localized into their languages — at the same time.

If your app targeting different users from different regions or you’re aiming for the global users, you might want to implement multiple languages within your app. Sadly, languages have different sentence structures. Some languages might prefer putting the Subject first, some prefer last. I also learned recently that most common languages are divided between Subject-Verb-Object and Subject-Object-Verb structure.
Example:
When user select apple I want my app to show sentence with user’s preferred language.Bahasa (Indonesian) : Anda memakan apel → ”You eat apple”Japanese: あなたはリンゴを食べます
(Anata wa ringo o tabemasu) →“You an apple eat”
In Bahasa, we need to replace the object at the end of the sentence while in Japanese it should be placed in the middle. My previous experience when working l10n on Java and C# has a similar solution: String.format
which behaves like printf
from C.
Here’s an example of how formatted string works:
// on English localization class
String youEat = "You eat %s";
String apple = "apple";// on Japanese localization class
String youEat = "あなたは%sを食べます";
String apple = "リンゴ";// on the app, refer the localization class
String.format(localization.youEat, localization.apple);
This will create sentence as first example above.
Now we talk about Dart. As per this article published, Dart does not have such built-in function. Dart already has string interpolation but that would not solve our problem. There’s already a sprintf-like dart packages, but I’d prefer to write simple function over adding new dependency.
To solve this, I need a function which:
- receives 2 arguments: a string template with placeholders and a list of values that will replace those placeholders. I set word wrapped in double-curly bracket as a placeholder pattern.
- replaces all placeholders with values from the list, orderly
- returns fully-replaced string
Then I came up with this:
This simple function goes well with Intl package from Dart team. You also can use any localization format, whatever suits your needs.