Search code examples
flutterflutter-layoutrichtextflutter-text

How to get the value of String in RichText Flutter?


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?


Solution

  • 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()}");
            },
          ),
        );
      }
    }