【问题标题】:FLUTTER: How to use text widget inside a stringFLUTTER:如何在字符串中使用文本小部件
【发布时间】:2020-07-31 11:19:16
【问题描述】:

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

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,以用正确的颜色打印正确的名称。

你知道怎么做吗?

【问题讨论】:

    标签: android ios flutter flutter-layout


    【解决方案1】:

    您可能正在寻找富文本小部件检查此

    RichText

    【讨论】:

      【解决方案2】:

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

      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 小部件来复制,但它不会是一行。

      【讨论】:

        猜你喜欢
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 2019-06-11
        • 2020-07-09
        • 2019-05-17
        • 2020-12-11
        相关资源
        最近更新 更多