如何获取RichText
Widget中String的值
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,
)
我想在RichText
中得到字符串的值,有人有办法做到吗?
您可以使用key从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()}");
},
),
);
}
}
您可以在TextSpan
的text
属性上提供如下字符串变量
String myText = "dot";
TextSpan(text: myText),