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

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

问题描述

有没有办法改变字符串中特定单词的颜色?

Text("一些长字符串")

现在我只想为 long 单词添加颜色.

谁能告诉我如何以编程方式做到这一点?

例如:-

<块引用>

我在某个变量中是一个很长很长的字符串,一个很长的字符串

现在我想在这里分开长词.我可以分开简单的字符串来突出显示一个单词,但不知道如何找到并突出显示这些单词中的每一个.

解决方案

将单词包装在 TextSpan 并分配 style 属性以更改文本外观并使用 RichText 而不是 Text

<块引用>

富文本(文本:文本跨度(文字:'你好',样式:DefaultTextStyle.of(context).style,孩子们:<TextSpan>[TextSpan(文本:'bold',样式:TextStyle(fontWeight:FontWeight.bold)),TextSpan(文本:'世界!'),],),)

或使用 Text.rich 构造函数 https://docs.flutter.io/flutter/widgets/Text-class.html

<块引用>

const Text.rich(文本跨度(text: 'Hello',//默认文本样式孩子们:<TextSpan>[TextSpan(text: '美丽', style: TextStyle(fontStyle: FontStyle.italic)),TextSpan(text: 'world', 风格: TextStyle(fontWeight: FontWeight.bold)),],),)

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

Text("some long string")

now i want to give color to only long word.

can someone tell me how can i do this programatically ?

eg:-

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.

解决方案

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!'),
    ],
  ),
)

or use the Text.rich constructor 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天全站免登陆