如何以编程方式突出显示字符串中的单词 [英] How to highlight a word in string in flutter programmatically

查看:84
本文介绍了如何以编程方式突出显示字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更改字符串中特定单词的颜色?

Is there any way to change color on particular word in a string ?

Text("some long string")

现在我只想给 long 单词加上颜色。

now i want to give color to only long word.

有人可以告诉我怎么做我以编程方式执行此操作?

can someone tell me how can i do this programatically ?

例如:-


我很久以前一个变量中的长字符串和长字符串,一个长字符串

I am long a really long and long string in some variable, a long one

现在在这里我想分隔长单词。
我可以将简单的字符串分开以突出显示一个单词,但不确定如何查找和突出显示每个单词。

now here i want to seperate long word. I can seperate simple string to highlight one word but not sure how to find and highlight each of these words.

推荐答案

将单词包装在 TextSpan 中,并分配样式属性来更改文本外观并使用 RichText 代替 Text

Wrap the word in a TextSpan and assign style properties to change the text appearance and use RichText instead of 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)),
    ],
  ),
)


这篇关于如何以编程方式突出显示字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆