π― Center vs Align in Flutter β What's the Difference?
When you're building layouts in Flutter, two of the most common widgets for positioning are Center
and Align
.
But which one should you use β and when?
Letβs break it down with simple examples π
π‘ 1. Center Widget
The Center
widget does exactly what it sounds like:
β
It centers its child both horizontally and vertically inside the available space.
πΉ Syntax:
Center(
child: Text("Hello Flutter"),
)
πΌοΈ Visual Example:
β Use Center when you just want to center something in its parent.
π’ 2. Align Widget
The Align widget gives you full control over where the child should be placed inside its parent using alignment.
πΉ Syntax:
Align(
alignment: Alignment.bottomRight,
child: Text("Hello Flutter"),
)
π― Alignment Options:
- Alignment.topLeft
- Alignment.topCenter
- Alignment.topRight
- Alignment.centerRight
- Alignment.center
- Alignment.centerLeft
- Alignment.bottomCenter
- Alignment.bottomRight
- Alignment.bottomLeft
- Alignment(-1, 0) β custom (X, Y)
Alignment values range from -1.0 (start) to 1.0 (end)
πΌοΈ Visual Example (bottomRight):
π So Whatβs the Difference?
Feature | Center |
Align |
---|---|---|
Positioning | Fixed center | Fully customizable |
Alignment | No parameters |
alignment: required |
Simplicity | Easiest for centering | Best for precise layout |
π§ When to Use What?
β
Use Center if you want to place a widget in the middle
β
Use Align if you need to place a widget anywhere else
β
Example Code: Try Both
Column(
children: [
Center(
child: Text("Centered"),
),
Align(
alignment: Alignment.bottomRight,
child: Text("Aligned Bottom Right"),
),
],
)
π¦ Conclusion
Both Center and Align are layout tools β but Align gives you more control.
Use Center when you can.
Use Align when you must.
Top comments (0)