Question #310EasyWidgets & UI

What is the purpose of the Stack widget in Flutter?

#flutter#widget#layout

Answer

Overview

The

text
Stack
widget lets you place children on top of each other, like layers. Children are positioned relative to the Stack's edges using the
text
Positioned
widget.


Basic Usage

dart
Stack(
  children: [
    // Bottom layer
    Container(
      width: 300,
      height: 200,
      color: Colors.blue,
    ),
    // Middle layer
    Container(
      width: 150,
      height: 100,
      color: Colors.red,
    ),
    // Top layer
    Text('On top!', style: TextStyle(color: Colors.white, fontSize: 20)),
  ],
)

Using Positioned

dart
Stack(
  children: [
    Image.network('https://example.com/photo.jpg'),
    Positioned(
      top: 16,
      right: 16,
      child: IconButton(
        icon: Icon(Icons.favorite, color: Colors.red),
        onPressed: () {},
      ),
    ),
    Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        color: Colors.black54,
        padding: EdgeInsets.all(8),
        child: Text('Caption here', style: TextStyle(color: Colors.white)),
      ),
    ),
  ],
)

Stack Alignment

dart
Stack(
  alignment: Alignment.center, // All non-positioned children go to center
  children: [
    CircleAvatar(radius: 50, backgroundColor: Colors.blue),
    Text('AB', style: TextStyle(color: Colors.white, fontSize: 24)),
  ],
)

Positioned Properties

dart
Positioned(
  top: 10,      // Distance from top edge
  bottom: 10,   // Distance from bottom edge
  left: 10,     // Distance from left edge
  right: 10,    // Distance from right edge
  width: 100,   // Fixed width (use instead of left+right)
  height: 100,  // Fixed height (use instead of top+bottom)
  child: Widget(),
)

// Fill entire Stack
Positioned.fill(child: Widget())

Common Use Cases

Use CaseStack Implementation
Badge on an icon
text
Stack → [Icon, Positioned(badge)]
Image with caption overlay
text
Stack → [Image, Positioned(caption)]
Floating action area
text
Stack → [Content, Positioned(FAB)]
Profile avatar with online dot
text
Stack → [CircleAvatar, Positioned(dot)]
Loading overlay
text
Stack → [Content, if loading: Overlay]

Clipping the Stack

dart
// Clip children that overflow the Stack bounds
ClipRect(
  child: Stack(
    clipBehavior: Clip.hardEdge, // Default
    children: [...],
  ),
)

Key Point: In a Stack, the last child is rendered on top. Use

text
Positioned
to place children at specific coordinates.