Mastering Stack and Positioned Widgets
๐งฑ Mastering Stack and Positioned Widgets in Flutter
๐ What is a Stack?
A Stack in Flutter is a widget that overlaps its children, meaning widgets can be placed on top of each other, like layers.
๐ง Why Use Stack?
Use Stack when you want to:
Place text over an image
Create floating buttons or badges
Position widgets in a free-form layout
๐ง Basic Syntax
dart
Copy
Edit
Stack(
children: <Widget>[
WidgetA(), // base layer
WidgetB(), // appears on top
],
)
๐บ️ Understanding Positioned
Positioned is used inside a Stack to place a child at a specific spot (like top-left, bottom-right, etc.).
dart
Copy
Edit
Stack(
children: [
Container(color: Colors.blue, width: 200, height: 200),
Positioned(
top: 10,
left: 20,
child: Text('Hello!'),
),
],
)
In the example above:
The blue box is the background.
The text appears 10 pixels from the top and 20 from the left.
๐งฉ Full Example
dart
Copy
Edit
Stack(
children: [
Image.asset('assets/photo.jpg'),
Positioned(
bottom: 10,
right: 10,
child: Container(
padding: EdgeInsets.all(5),
color: Colors.black54,
child: Text(
'Caption',
style: TextStyle(color: Colors.white),
),
),
),
],
)
๐ฏ Use Case: Placing a caption on the bottom-right of an image.
⚙️ Additional Features
๐ Alignment Without Positioned
You can align children inside a Stack using the Alignment property:
dart
Copy
Edit
Stack(
alignment: Alignment.center,
children: [
Container(color: Colors.red, width: 100, height: 100),
Icon(Icons.star, size: 50),
],
)
The icon is centered over the red box.
๐ Common Properties
Stack
Property Description
alignment Aligns children inside the stack (e.g., Alignment.topRight)
fit Controls how non-positioned children are sized (loose or expand)
clipBehavior Controls how overflow is handled
Positioned
Property Description
top / bottom / left / right Distance from the corresponding edge
width / height Set size of the widget manually
❗ Best Practices
Don’t overuse Stack—it's powerful, but complex layouts are harder to maintain.
Use SafeArea if positioning near screen edges.
Test on multiple screen sizes if using fixed pixel values.
Combine Stack with MediaQuery or LayoutBuilder for responsive designs.
✅ Summary
Concept Purpose
Stack Layer widgets on top of each other
Positioned Place widgets exactly where you want inside the stack
alignment Control child alignment without positioning
Use case Image overlays, floating widgets, custom layouts
Learn Flutter Training in Hyderabad
Read More
Using Rows and Columns in Flutter
Creating Responsive Layouts in Flutter
Working with Text and Images in Flutter
Comments
Post a Comment