What is a Stack?
Normally widgets sit next to each other. A Stack lets them sit on top of each other, like papers on a desk. The first child is at the bottom, and the last child is on top.
dart
Stack(
children: [
Container(width: 200, height: 200, color: Colors.blue),
Container(width: 140, height: 140, color: Colors.green),
Container(width: 80, height: 80, color: Colors.orange),
],
)
Positioned
Positioned places a child at an exact distance from the edges of the Stack.
dart
SizedBox(
width: 300,
height: 200,
child: Stack(
children: [
Positioned.fill(
child: Image.network('https://picsum.photos/400/300', fit: BoxFit.cover),
),
const Positioned(
left: 16,
bottom: 16,
child: Text(
'Beautiful View',
style: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold),
),
),
const Positioned(
top: 8,
right: 8,
child: Icon(Icons.favorite, color: Colors.red),
),
],
),
)
Rule: Positioned must be a direct child of a Stack. Putting it inside a Row or Column causes an error.
Align in a Stack
dart
Stack(
children: const [
Align(alignment: Alignment.topLeft, child: Text('Top Left')),
Align(alignment: Alignment.center, child: Text('Center')),
Align(alignment: Alignment.bottomRight, child: Text('Bottom Right')),
],
)
A Notification Badge
dart
Stack(
clipBehavior: Clip.none,
children: [
const Icon(Icons.shopping_cart, size: 36),
Positioned(
right: -6,
top: -6,
child: Container(
padding: const EdgeInsets.all(5),
decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
child: const Text('3', style: TextStyle(color: Colors.white, fontSize: 12)),
),
),
],
)
clipBehavior: Clip.none lets the badge go outside the Stack's borders without being cut. In Material 3 you can also use the ready-made Badge widget.
Useful Properties
| Property | Meaning |
alignment | Where non-positioned children go (default top left) |
fit | StackFit.expand makes children fill the Stack |
clipBehavior | Cut or show children outside the box |
Conclusion
Use Stack when widgets must overlap. Positioned gives exact placement and Align gives relative placement.
Quick Summary: Stack layers children, Positioned sets edges, and Positioned must be directly inside a Stack.