Align vs Positioned in Flutter: Understanding When and How to Use Them
Blog Author : Sourav Sonkar
When building Flutter UIs, positioning widgets precisely is a common need. Two widgets often used for this are Align and Positioned. While both are used to control where a widget appears, they serve different purposes and behave differently. In this post, we'll explore their differences, best use cases, and practical examples to make the right choice every time.
Understanding the Basics
Align Widget
Positioned Widget
Key Differences at a Glance
| Feature | `Align` | `Positioned` |
| ----------- | -------------------------------------------------- | ----------------------------------------------- |
| Used Inside | Any layout (commonly `Container`, `Column`, etc.) | Only inside a `Stack` |
| Positioning | Relative using `alignment` | Absolute using `top`, `left`, `right`, `bottom` |
| Sizing | Can scale child with `widthFactor`, `heightFactor` | Does not alter child size |
| Use Case | Aligning elements like buttons, text, etc. | Creating floating buttons, tooltips, badges |
Real-World Example 1: Aligning a Login Button
Let’s say you’re creating a login screen and you want the “Login” button to always stay at the bottom center of the screen, regardless of screen size.
Scaffold(
body: Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: ElevatedButton(
onPressed: () {},
child: Text('Login'),
),
),
),
)
Why Align?
Real-World Example 2: Overlay a Badge on an Icon
You want to show a small red badge on the top-right of a shopping cart icon. This is a classic use of Stack and Positioned.
Stack(
children: [
Icon(Icons.shopping_cart, size: 40),
Positioned(
right: 0,
top: 0,
child: Container(
padding: EdgeInsets.all(4),
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
child: Text(
'3',
style: TextStyle(color: Colors.white, fontSize: 12),
),
),
),
],
)
Why Positioned?
Conclusion
Both are powerful tools in your Flutter UI toolkit. Choosing the right one depends on your layout needs.
For more details, refer to the official Flutter documentation on Align Widget and Positioned Widget.