What is the purpose of the Stack widget in Flutter?
#flutter#widget#layout
Answer
Overview
The widget lets you place children on top of each other, like layers. Children are positioned relative to the Stack's edges using the textStack
text
PositionedBasic Usage
dartStack( 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
dartStack( 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
dartStack( 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
dartPositioned( 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 Case | Stack Implementation |
|---|---|
| Badge on an icon | text |
| Image with caption overlay | text |
| Floating action area | text |
| Profile avatar with online dot | text |
| Loading overlay | text |
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
to place children at specific coordinates.textPositioned