How to get the value of String in RichText Flutter?

1.7k Views Asked by At

How to get the value of String in RichText Widget.

RichText(
  text: TextSpan(
    style: TextStyle(color: Colors.black, fontSize: 36),
    children: <TextSpan>[
      TextSpan(text: 'Woolha ', style: TextStyle(color: Colors.blue)),
      TextSpan(text: 'dot '),
      TextSpan(
          text: 'com',
          style: TextStyle(decoration: TextDecoration.underline))
    ],
  ),
  textScaleFactor: 0.5,
)

I want to get the value of String in RichText, does anyone have a way to do it?

2

There are 2 best solutions below

1
On BEST ANSWER

You can use key to extract text from RichText.

final RichText? richText = richTextKey.currentWidget as RichText?;

debugPrint("${richText?.text.toPlainText()}");
class GettingRichText extends StatelessWidget {
  GettingRichText({Key? key}) : super(key: key);

  final richTextKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RichText(
        key: richTextKey,
        text: const TextSpan(
          style: TextStyle(color: Colors.black, fontSize: 36),
          children: <TextSpan>[
            TextSpan(text: 'Woolha ', style: TextStyle(color: Colors.blue)),
            TextSpan(text: 'dot '),
            TextSpan(
                text: 'com',
                style: TextStyle(decoration: TextDecoration.underline))
          ],
        ),
        textScaleFactor: 0.5,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          final RichText? richText = richTextKey.currentWidget as RichText;

          debugPrint("${richText?.text.toPlainText()}");
        },
      ),
    );
  }
}

2
On

You can provide String variable on text property of TextSpan something like below.

String myText = "dot";

TextSpan(text: myText),