【问题标题】:How can I align TextSpan children which have different sizes, along the middle in Flutter?如何在 Flutter 中沿中间对齐具有不同大小的 TextSpan 子项?
【发布时间】:2021-06-15 06:58:13
【问题描述】:

根据附加的图像,我有三个 TextSpan 子对象 - 中间的 TextSpan 对象的字体更大。

我希望所有三个 TextSpan 对象都以背景父对象为中心。

当字体大小相同时,它们沿中心水平对齐。但是,当我增加一个 TextSpan 的字体大小时,只有较大的文本对象保持居中,较小的两个字体落在较大字体的基础上)...

我尝试了不同的对齐属性,但无法解决。这可以用 TextSpan 文本完成吗?

谢谢!

    return Container(
      decoration: BoxDecoration(
        color: Colors.amber,
      ),
        alignment: Alignment.center,
        child: RichText(
          textAlign: TextAlign.center,
          text: TextSpan(
            children: [
              TextSpan(text: 'Let\s', style: TextStyle(
                fontSize: 30,
              )),
              TextSpan(text: '500', style: TextStyle(fontSize: 80), ),
              TextSpan(text: 'Words', style: TextStyle(
                fontSize: 30,
              )),
            ]
          ),
        )
        );

【问题讨论】:

    标签: flutter text


    【解决方案1】:

    您可以使用WidgetSpans 来确保您的所有元素(文本与否)都垂直居中

    Container(
      decoration: BoxDecoration(
        color: Colors.amber,
      ),
      alignment: Alignment.center,
      child: RichText(
        text: TextSpan(
          children: [
            buildCenteredTextSpan(text: 'Let\s', style: TextStyle(fontSize: 30)),
            buildCenteredTextSpan(text: '500', style: TextStyle(fontSize: 80)),
            buildCenteredTextSpan(text: 'Words', style: TextStyle(fontSize: 30)),
          ],
        ),
      ),
    ),
    

    buildCenteredTextSpan:

      WidgetSpan buildCenteredTextSpan({required String text, required TextStyle style}) {
        return WidgetSpan(
          alignment: PlaceholderAlignment.middle,
          child: Text(text, style: style),
        );
      }
    

    【讨论】:

    • 太棒了!我刚刚使用上述解决方案编辑了我的代码并且它有效。感谢您的快速答复!干杯。
    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    相关资源
    最近更新 更多