I need to work with .arb files for internalization in Flutter, and I am interesting is possible to use string format with %s, and integer format with %d in Flutter, such in Java, C#, Python, etc. I want for example this string in app_en.arb
{
"ocrMessage": "User with name %s found in the database. Would you like to select and edit them?"
}
I was searching Flutter documentation and Google, but I did not find anything about formatting strings in Flutter, only string interpolation, eg:
var myName = "Darko";
Print("Your name is $myName");
Thank you very much.
Best regards,
Darko
CodePudding user response:
sprintf: ^6.0.0 Use this package
var me = {
"ocrMessage":
"User with name %s found in the database. Would you like to select and edit them?"
};
print(sprintf(me["ocrMessage"].toString(), [100]));
Output:
User with name 100 found in the database. Would you like to select and edit them?
CodePudding user response:
you're right, the most common way to format a string in Dart/Flutter is using a string interpolation. As outlined by @lava, there are packages like sprintf
to add your desired behavior. But as I
understand your question, you would like to find a way to insert a dynamic value into your translations. If so, arb files provide a simple way to define placeholders that you can use in your string. The following is an example for your ocrMessage
with a varying firstName
:
"ocrMessage": "User with name {firstName} found in the database. Would you like to select and edit them?",
"@ocrMessage": {
"description": "A user's first name",
"placeholders": {
"firstName": {}
}
}
After running the code generator, you'll get access to your translation by using the following (assuming that your localization delegate class is named AppLocalizations):
AppLocalizations.of(context)!.ocrMessage("Darko")
As the parameters of the generated code will be of type Object, you can add basically anything you want (except null) that can be transformed to a string.
Hope this solves your question!