Home > Software design >  How to get the value of String in RichText Flutter?
How to get the value of String in RichText Flutter?

Time:04-27

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?

CodePudding user response:

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

CodePudding user response:

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

String myText = "dot";

TextSpan(text: myText),
  • Related