Problem Statement
How do Stack and Positioned widgets work together? Explain with examples of common use cases.
Explanation
Stack overlays children in paint order where first child is drawn first (bottom layer) and subsequent children are drawn on top. Positioned widget, used as Stack children, specifies exact positions using top, bottom, left, and right properties measured from Stack edges. If a property is not specified, the child is positioned relative to other specified properties or centered if none are specified.
For example, Positioned(top: 10, left: 10, child: Icon(Icons.star)) places an icon 10 pixels from top and left edges. Positioned.fill makes a child fill the entire Stack. Use Positioned.directional for RTL-aware positioning. Children without Positioned are sized by Stack's constraints and aligned according to Stack's alignment property (default Alignment.topLeft).
Common use cases include badges on icons using Stack with main widget and a Positioned badge in the corner, overlaying loading indicators on content, creating custom app bars with background images and overlaid text, building complex cards with layered content, and creating custom layouts where widgets overlap like profile pictures with edit buttons or image galleries with captions overlaid on images.
Stack can use fit property to control how non-positioned children are sized: StackFit.loose (default) sizes children to their natural size within constraints, StackFit.expand forces non-positioned children to fill the Stack, and StackFit.passthrough passes constraints unchanged. Use clipBehavior to control whether children outside Stack bounds are clipped. Understanding Stack and Positioned is essential for creating sophisticated overlapping layouts.
