Search code examples
fluttertextfieldvertical-alignmentrichtext

RichText containing TextField: vertical alignment


I would like to use a RichText widget containing TextSpans as well as inline TextFields (inside WidgetSpans). The TextField text should be aligned to the same vertical baseline as the TextSpans.

How is it possible to achieve this vertical alignment?

I use the following code:

RichText(
        text: TextSpan(style: TextStyle(color: Colors.black), children: [
      TextSpan(text: "Text1 "),
      WidgetSpan(
          child: SizedBox(
              width: 50,
              child: TextField(
                decoration: InputDecoration(hintText: "input"),
              ))),
      TextSpan(text: " Text2")
    ]));

This leads to the following appearance:

misaligned TextField

This is how it should look:

aligned TextField


Solution

  • You can provide PlaceholderAlignment on WidgetSpan.

    WidgetSpan(
      alignment: PlaceholderAlignment.baseline,
    

    The TextFiled height is greater than the text height, you can wrap with a SizedBox. Also I would suggest to play with Baseline for this.

    Baseline(
      baseline: 50,
      baselineType: TextBaseline.alphabetic,
      child: RichText(
        text: TextSpan(
          style: TextStyle(color: Colors.black),
          children: [
            TextSpan(text: "Text1 "),
            WidgetSpan(
              alignment: PlaceholderAlignment.baseline,
              baseline: TextBaseline.alphabetic,
              child: SizedBox(
                width: 50,
                height: 30,
                child: TextField(
                  decoration: InputDecoration(hintText: "input"),
                ),
              ),
            ),
            TextSpan(text: " Text2")
          ],
        ),
      ),
    ),