How do I center text vertically and horizontally in Flutter?

In Flutter, aligning text both vertically and horizontally to the center can be a bit tricky. However, with a little knowledge of the Text widget’s properties, you can achieve this easily.

Why doesn’t Center widget work for vertical alignment?

The Center widget in Flutter is used to align its child widgets both horizontally and vertically to the center. However, when it comes to text, using a Center widget alone won’t work as expected. This is because the Text widget itself doesn’t understand how to be centered vertically.

The code you might initially think would work is:

child: Center(
  child: Text(
    "Hello World",
    textAlign: TextAlign.center,
  ),
)

This will only center the text horizontally, not vertically. This is because the textAlign property of the Text widget only deals with horizontal alignment.

Using TextAlign property for vertical and horizontal centering

As you’ve seen in your own code snippet, using the textAlign property of the Text widget itself is not enough. However, it’s actually very close! You can use the following code to achieve both vertical and horizontal text alignment:

child: Center(
  child: Text(
    "Hello World",
    textAlign: TextAlign.center,
    textDirection: TextDirection.ltr, // or TextDirection.rtl
  ),
)

Wait, what? You’ve added another property called textDirection. Yes! That’s the key. The textAlign property alone would only work if you used a Container widget with a specific height to wrap your text and then centered that container using the Center widget. However, using the textDirection property allows us to specify whether we’re working in a left-to-right or right-to-left context.

In most cases, you would use TextDirection.ltr, but if you’re working with languages that read from right to left like Arabic or Hebrew, you’d use TextDirection.rtl. This tells the widget how to determine which end is up and whether text should be aligned to the left or right edge of its parent.

A better solution using Container and Center widgets together

Now that we’ve explored why our initial code snippet didn’t work, let’s create a proper solution. If you have text and want it both vertically and horizontally centered within a Container, here is what works:

child: Container(
  height: 200,
  child: Center(
    child: Text(
      "Hello World",
      textAlign: TextAlign.center,
    ),
  ),
)

This way, you’re explicitly setting the height of your text container and then using Center widget to center its child vertically. This will ensure that all text within that container is displayed at the vertical center.

Conclusion

In Flutter, achieving both horizontal and vertical text alignment involves a bit more effort than using the textAlign property of the Text widget. By utilizing the textDirection property or combining the Container and Center widgets, you can easily ensure that your text is displayed exactly how you want it to be.