Reputation: 4091
The package intl
exists to localize the flutter application but the Intl.message
only returns String
How can I have a rich content localization?
Hello $name!
, and make only $name
bold, Consider that the order of hello and $name can be different in different languagesI read terms of services and accepted it
, and link only terms of services
partin [TEXT_INPUT] days
, the [TEXT_INPUT] has a text after and a text before, but in some languages there is no 2 text, just one text after or before, or days
is before and in
is after [TEXT_INPUT]
Upvotes: 7
Views: 3885
Reputation: 4440
The slang package has built-in rich text support.
It will look like this:
{
"myRichText(rich)": "Welcome {name}"
}
Widget a = Text.rich(t.myRichText(
// Show name in blue color
name: TextSpan(text: 'Tom', style: TextStyle(color: Colors.blue)),
));
Upvotes: 3
Reputation: 41793
Have a look at the styled_text package. You get to specify the text (content) separately from the formatting, witch allows you to use standard i18n approaches.
Text format is specified as tags wich you can define globally (e.g. in a resource class) and then use everywhere. Sounds like a good solution to me.
Example (from the Readme):
StyledText(
text: 'Test: <bold>bold</bold> text.',
tags: {
'bold': const StyledTextTag(style: const TextStyle(fontWeight: FontWeight.bold)),
},
)
will display like:
Test: bold text.
If you use the i18n package and a resource class instance R
for the tags, this might look like:
StyledText(
text: S.testBoldText,
tags: R.styledTextTags,
);
Just keep in mind that the tags need to be preserved in translation.
Upvotes: 8
Reputation: 828
Here is an example of how you can inject variables into your translation.
"hello_name": "Hello {name}",
"@hello_name": {
"placeholders": {
"name": {
"type": "String"
}
}
},
This will generate a function hello_name
for you to pass name
There is no styling support but if you need it then just don't use placeholders
like in the above example and have your text be separate and style it using RichText
where you specify what parts of your text need to have what styling. You don't need to worry about directionality as it will be handled for you depending on your local.
Upvotes: 1