繁体   English   中英

FLUTTER:如何在字符串中使用文本小部件

[英]FLUTTER: How to use text widget inside a string

我有一个这样的文本小部件列表:

List<Widgets> widgets = [
    Text('Theo', style: TextStyle(color: Colors.green)),
    Text('Luca', style: TextStyle(color: Colors.blue))
]

我有这样的字符串列表:

'My name is @name',
'@name how old are you ?'

我想用列表中的文本小部件替换@name以用正确的颜色打印正确的名称。

你知道一种方法吗?

Text Widget 中是不可能的,请使用将TextSpan作为子级的RichText Widget。

将文本更改为Text Text Span

List<Widgets> widgets = [
    TextSpan(text: 'Theo', style: TextStyle(color: Colors.green)),
    TextSpan(text: 'Luca', style: TextStyle(color: Colors.blue))
]

每行都是一个RichText RichText 将TextSpan作为子项,其中必须指定文本和相应的样式。

widgets.map((textSpan) {
  return Column(
    children: [
      RichText(
      text: TextSpan(
        text: 'My name is ',
        style: DefaultTextStyle.of(context).style,
        children: <TextSpan>[
          textSpan // Name with color will appear here
        ],
      ),
      RichText(
        children: <TextSpan>[
          textSpan // Name with color will appear here
          TextSpan (
             text: 'How old are you? ',
             style: DefaultTextStyle.of(context).style,
           ),
        ],
      ),
    ],
  )
}

或者,这可以通过使用 Row 和 Text 小部件来复制,但它不会是一行。

你可能正在寻找富文本小部件检查这个

富文本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM