How to localize text with TextSpan widget?

175

EDIT: More explanation The text can not be handled as one piece. Each part of needs to be handled separately. Because from the TextSpans concern, those are different texts. So you need to create two different texts within the arb file.

From the Flutter Intl's perspective, these are two different components. TextSpan has its own drawing perspective. That is why you need to create two different components for these items.

There are packages out there like https://pub.dev/packages/localized_rich_text but I did not use it. In our app I use it like the following.

Flutter Intl creates the localized elements as follows:

AppLocalizations.of(context).tranlatedElement;

//or
AppLocalizations.current.tranlatedElement;

So your Code should be like the following

Text.rich(
   TextSpan(
     text: AppLocalizations.current.relaxTextPrefix,
     children: [
       TextSpan(
         text: AppLocalizations.current.relaxTextSuffix,
         style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
         ),
       ),
     ],
   ),
 ),
)
Share:
175
Nayan Babariya
Author by

Nayan Babariya

Updated on January 03, 2023

Comments

  • Nayan Babariya
    Nayan Babariya over 1 year

    I am using Flutter Intl android studio plugin for ready made localization. But in my scenario i have the widget like this,

    Text.rich(
          TextSpan(
            text: 'It is time to',
            children: [
              TextSpan(
                text: 'Stay Relaxed',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        )
    

    So how can i translate a single message "It is time to Stay Relaxed" and use in Text.rich widget?

  • Nayan Babariya
    Nayan Babariya about 2 years
    Can you please elaborate what is meaning of tranlatedElement and relaxTextPrefix?
  • salihgueler
    salihgueler about 2 years
    Of course, I will write here and explain it in the question as well. The text can not be handled as one piece. Each part of needs to be handled separately. Because from the TextSpans concern, those are different texts. So you need to create two different texts within the arb file.