如何在 Flutter 中将具有不同大小的 TextSpan 子项沿中间对齐?

Kdo*_*don 2 text flutter

根据所附图像,我有三个 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,
              )),
            ]
          ),
        )
        );

Run Code Online (Sandbox Code Playgroud)

Rao*_*che 5

您可以使用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)),
      ],
    ),
  ),
),
Run Code Online (Sandbox Code Playgroud)

buildCenteredTextSpan

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

在此输入图像描述