如何以编程方式突出显示字符串中的单词
问题内容:
有什么方法可以改变字符串中特定单词的颜色?
Text("some long string")
现在我只想给 长 字加颜色。
有人可以告诉我我该如何编程吗?
例如:-
我是一个很长很长的字符串,包含一些变量,很长
现在在这里我想分开长词。我可以将简单的字符串分开以突出显示一个单词,但不确定如何找到并突出显示每个单词。
问题答案:
将单词包装在TextSpan中,并分配style
属性以更改文本外观,并使用RichText代替Text
> RichText(
> text: TextSpan(
> text: 'Hello ',
> style: DefaultTextStyle.of(context).style,
> children: <TextSpan>[
> TextSpan(text: 'bold', style: TextStyle(fontWeight:
> FontWeight.bold)),
> TextSpan(text: ' world!'),
> ],
> ),
> )
或使用Text.rich
构造函数https://docs.flutter.io/flutter/widgets/Text-
class.html
>
> const Text.rich(
> TextSpan(
> text: 'Hello', // default text style
> children: <TextSpan>[
> TextSpan(text: ' beautiful ', style: TextStyle(fontStyle:
> FontStyle.italic)),
> TextSpan(text: 'world', style: TextStyle(fontWeight:
> FontWeight.bold)),
> ],
> ),
> )
>