Flutter-如何使用某种生成器在同一段落中以不同的样式显示字符串数组?

问题描述

您所能提供的任何帮助将不胜感激。我无法弄清楚。

我将处理JSON数据文件,其中包含不同的字符串数组,我们希望所有这些字符串都显示在同一单个段落中。需要以编程方式遍历数组以动态创建显示的小部件。

该段落将包含要以普通文本,粗体和斜体显示的单词。 (我们可以在结构的第二个参数中提供类型,但稍后会提供更多信息。)

我可以在Flutter中手动执行此操作,如下所示:

enter image description here

这是创建此代码的代码片段: (我在这里对数据数组进行了复制...真正的数据数组将在运行时读取。)

List data = [
    "For example,","this(1)"," is bold. And ","this(2)"," is italic. And,finally ","this(3)"," is bold and italic."
];
                          
 return Text.rich(
             TextSpan(
                  text: '',children: 
                      <InlineSpan>[
                         TextSpan(
                              text: data[0],),TextSpan(
                              text: data[1],style: TextStyle(fontWeight: FontWeight.bold,TextSpan(
                                  text: data[2],TextSpan(
                                  text: data[3],style: TextStyle(fontStyle: FontStyle.italic),TextSpan(text: data[4]),TextSpan(
                                    text: data[5],style: TextStyle(
                                        fontWeight: FontWeight.bold,fontStyle: FontStyle.italic)),TextSpan(text: data[6]),],);


但是,我需要在运行时以编程方式创建小部件(使用某种生成器功能或类似的功能)。

曾尝试使用RichText和Tech.rich,但无济于事。此外,找不到有关ParagraphBuilder的任何有用示例(找到了类描述,但这还不够有用)。

有人知道如何在Flutter的单个段落中从数组/列表/映射中来做类似的事情

非常感谢您吗?

下面显示了一个数据数组和手动工作的代码的示例(撇开了如何准确提供样式类型的问题。在弄清楚如何在相同的字符串中显示之后,我可以进行探讨数组中的段落)。

解决方法

要在列表中生成小部件,可以使用简单的for循环:

<InlineSpan>[
  for(var string in data)
    TextSpan(text: string),]
,

感谢@MickaelHrndz和@psink

@MickaelHmdz-效果很好!!!非常感谢!

这是第一部分的相关代码-将数组/字符串列表放入同一段落:

var list = [
      "one asdfads","two fasdf aeer","three asdf 23v ar uppo  ","four aspl ojv mepfif hepv,"
    ];      

...

body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: RichText(
          text: TextSpan(children: <InlineSpan>[
            for (var string in list)
              TextSpan(text: string,style: TextStyle(color: Colors.black)),]),),

这是手机上结果的屏幕截图:

enter image description here

更新:使用三元运算符来处理。

中的样式。

完美搭配样式!!!!谢谢你们!

以下是更新的结果:

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...