How can I align TextSpan children which have different sizes, along the middle in Flutter?

Viewed 459

I have three TextSpan children as per the image attached - with the middle TextSpan object a larger font size.

I want all three TextSpan objects to be centered against the background parent.

When the fonts are all the same size they are aligned along the center horizontally. However when I increase the font size of one TextSpan, only the larger text object remains centered and the smaller two fonts fall to the larger font's base)...

I have tried different alignment properties but cannot work it out. Can this be done with TextSpan text?

Thanks!

screenshot

    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,
              )),
            ]
          ),
        )
        );

1 Answers

You can use WidgetSpans to make sure all your elements(text or not) are vertically centered

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)),
      ],
    ),
  ),
),

and buildCenteredTextSpan:

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

enter image description here

Related