How to align widgets in Flutter: Part 1

Share this post

You can find Part 2 here

I remember when I started using Flutter, there were a lot of use cases in terms of alignment, where I didn’t know exactly how to approach them. I think alignment of widgets is one of the most important parts in Flutter UI (as it is in web development) and Flutter made it terribly easy to do so, given that you know the right widgets/approach to use.

In this series, I won’t go very deep into the technical details of each widget that I describe but rather will give practical examples with use cases.

How to align single widgets in Flutter

For this use case, we can use the Align widget which lets us align our widget in 9 places in the parent widget:

  • topLeft
  • topCenter
  • topRight
  • centerLeft
  • center
  • centerRight
  • bottomLeft
  • bottomCenter
  • bottomRight

We just need to define what alignment we want and what widget we want to align. In this case, we choose for Alignment.topCenter and we are aligning a Container with a Text as the child.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Align(
        alignment: Alignment.topCenter,
        child: Container(
          color: Colors.lightBlue,
          child: Text(
            'mrflutter.com',
            style: TextStyle(
              fontSize: 30,
            ),
          ),
        ),
      ),
    );
  }

Which will obviously look like this:

Single widget alignment in Flutter
Alignment.topCenter

Or we could try Alignment.centerLeft, which will look like this:

Single widget alignment in Flutter
Alignment.centerLeft

You can try other variants of alignment and see what happens. I think you get the idea. For Alignment.center, there is a shortcut available and that will be a bridge to our next use case.

How to center a widget horizontally and vertically in Flutter

There is a very useful widget called Center that takes a child widget and aligns it in the center of the parent widget. This works exactly the same as the Align widget with Alignment.center parameter.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Container(
          color: Colors.lightBlue,
          child: Text(
            'mrflutter.com',
            style: TextStyle(
              fontSize: 30,
            ),
          ),
        ),
      ),
    );
  }