Search code examples
stringfluttertextrichtextstyledtext

Flutter "styled_text" package: how to get (displayed) text from StyledText() widget?


I have figured out a solution just as I was about to post this question. I will still post it, along with my own answer, to help anyone who might need this in the future

I use the styled_text package in my project, which makes it easier to create rich text than with the native Flutter Richtext() widget.

Have a look at this code example:

String name = 'Cedric';
StyledText myStyledText = StyledText(
  text: "Hello <name/>, <b>bold text</b>",
  tags: {
    'b': StyledTextTag(style: TextStyle(fontWeight: FontWeight.bold)),
    'name': StyledTextWidgetTag(Text(name)),
  },
);

The StyledText widget in this case would display something that looks like:

Hello Cedric, bold text

I don't care about the bold, or italic, color or any other styling attribute right now. What I need is to be able to get the text that would be displayed by the widget (with my name that I have injected), as a String.
myStyledText.text in this case would return Hello <name/>, <b>bold text</b>.
What I want to get is Hello Cedric, bold text, as a String.

The reason I need this, is because I want to use it in a Tooltip widget, which takes a String (and not Widget) parameter message, which will be displayed as a tooltip.


Solution

  • This will properly display "Hello Cedric" in the tooltip.

    Tooltip(
      triggerMode: TooltipTriggerMode.tap,
      showDuration: Duration(seconds: 2),
      // message: 'message test',
      richMessage: WidgetSpan(
          child: StyledText(
        text: "Hello <name/>",
        tags: {
          'name': StyledTextWidgetTag(
            Text('Cedric', style: TextStyle(color: Colors.black)),
          ),
        },
        style: TextStyle(color: Colors.black),
      )),
      child: Icon(Icons.info_outline, color: Colors.blue),
    ),