Sub topic 12
How a Stack sizes itself, aligns children, and clips
This chapter assumes you know how box constraints work (constraints go down, sizes go up) and how Positioned places a child. Here you will learn three behaviors of Stack that cause most surprises: how it chooses its own size, how alignment places children, and what clipBehavior does to children that stick out.
How a Stack chooses its size
A Stack splits its children into two groups:
- Non-positioned children are any child that is not wrapped in
Positioned. They take part in sizing. - Positioned children are wrapped in
PositionedorPositioned.fill. They never affect the Stack's size. The Stack sizes itself first, then places them.
The rules are:
- If the Stack has at least one non-positioned child, it sizes itself to fit the largest of them, clamped to the parent's constraints.
- If every child is positioned, the Stack has nothing to measure. It expands to the biggest size its constraints allow.
The two code samples from the plan show each case. In the first, the Stack gets its size from a SizedBox. Both children are positioned, so they do not size it.
SizedBox(
width: 200,
height: 200,
child: Stack(
children: [
Positioned.fill(
child: ColoredBox(color: Colors.grey),
),
Positioned(
right: 8,
bottom: 8,
child: Icon(Icons.favorite, color: Colors.red),
),
],
),
)The SizedBox passes tight 200 by 200 constraints, so the Stack is 200 by 200. Without the SizedBox, this Stack would fill whatever space its parent allowed.
In the second sample, the blue Container is non-positioned, so it sets the Stack's size.
Stack(
alignment: Alignment.center,
children: [
Container(width: 120, height: 120, color: Colors.blue),
const Text('Hi'),
],
)The Stack is 120 by 120. The Text is smaller, so it does not change the size. Swap the order of the children and the Stack is still 120 by 120, but the text is now painted underneath the blue box and is hidden.
Stacks with only positioned children in unbounded space
A Stack made only of positioned children asks for the biggest size available. Inside a Column or a vertical ListView, the height is unbounded, so the biggest size is infinite and Flutter reports an error. Give the Stack a fixed size with SizedBox, AspectRatio, or a non-positioned child that has an intrinsic size.
Controlling how non-positioned children are constrained with fit
The fit property decides which constraints non-positioned children receive. It does not affect positioned children.
| `StackFit` | Constraints given to non-positioned children | Typical use |
|---|---|---|
| `loose` (default) | From zero up to the Stack's maximum. Children can be smaller than the Stack. | Badge over an image, text over a box |
| `expand` | Tight at the largest size the Stack's constraints allow. Every child is forced to fill. | Full-bleed backgrounds |
| `passthrough` | The Stack's own incoming constraints, unchanged. | Stacks whose parent already gives tight constraints |
Here is a complete app that uses StackFit.expand. The Stack is 240 by 140 because of the SizedBox. The colored Container has no size of its own, and expand forces it to fill the Stack.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: Banner140()))));
class Banner140 extends StatelessWidget {
const Banner140({super.key});
@override
Widget build(BuildContext context) {
return SizedBox(
width: 240,
height: 140,
child: Stack(
fit: StackFit.expand,
children: [
Container(color: Colors.teal),
const Align(
alignment: Alignment.bottomLeft,
child: Padding(
padding: EdgeInsets.all(12),
child: Text(
'Weekend sale',
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
],
),
);
}
}With the default StackFit.loose, the Container would have no child and no size, so it would shrink to nothing and the teal background would not appear.
Aligning children with alignment
The alignment property places children that do not specify their own position. Its default is AlignmentDirectional.topStart, which is the top-left corner in left-to-right languages and the top-right in right-to-left languages.
An Alignment is a point in a coordinate system where (-1, -1) is the top-left corner, (0, 0) is the center, and (1, 1) is the bottom-right corner. Constants such as Alignment.center and Alignment.bottomRight name common points.
Alignment applies in these cases:
- Every non-positioned child is aligned by
alignment. In the "Hi" sample,Alignment.centercenters the text on the blue box. - A positioned child is aligned on any axis where you gave no constraint. For example,
Positioned(top: 8, child: ...)has noleft,right, orwidth, so its horizontal position comes fromalignment.
If you need an item in the corner of an otherwise centered Stack, a positioned child is the more explicit choice. Use alignment for the common placement and Positioned for exceptions.
Clipping with clipBehavior
By default, a Stack uses Clip.hardEdge. Anything that extends past the Stack's bounds is cut off. This is a common source of "my badge is half missing" bugs.
The usual case is a notification badge that deliberately sits outside the corner of its parent. Set clipBehavior: Clip.none to let it paint outside:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: BadgeDemo()))));
class BadgeDemo extends StatelessWidget {
const BadgeDemo({super.key});
@override
Widget build(BuildContext context) {
return Stack(
clipBehavior: Clip.none,
children: [
Container(width: 80, height: 80, color: Colors.indigo),
Positioned(
top: -8,
right: -8,
child: CircleAvatar(
radius: 12,
backgroundColor: Colors.red,
child: const Text('3', style: TextStyle(fontSize: 12)),
),
),
],
);
}
}The Stack is 80 by 80 because of the indigo box. The badge has negative offsets, so half of it lies outside the Stack. With the default clip, the outer half is cut away. With Clip.none, the badge paints in full.
| `Clip` value | Effect | Cost |
|---|---|---|
| `Clip.hardEdge` (default) | Cuts at the Stack's rectangle without smoothing | Low |
| `Clip.antiAlias` | Cuts with smoothed edges | Higher |
| `Clip.antiAliasWithSaveLayer` | Smoothed, with an offscreen layer | Highest, rarely needed |
| `Clip.none` | No clipping | None |
Hit testing does not follow painting
Clip.none changes only what is painted. Taps are still tested against the Stack's own rectangle. A button positioned outside the Stack's bounds shows up on screen, but taps on the outside part do nothing, because the Stack does not pass them to its children.
To fix this, make the Stack large enough to contain the child. A common method is to wrap the content in Padding so the Stack's box includes the badge area, then position the badge inside that padded box.
Painting and hit-testing order
Children paint in list order, so the last child is on top. Hit testing works in the reverse direction. Flutter offers a tap to the topmost child first, then to lower children if the upper ones do not claim it. To reorder layers, change the order of the list. There is no z-index property.
Common mistakes with sizing, alignment, and clipping:
- Putting a full-size background
Containerin a loose Stack withoutPositioned.fillorStackFit.expand, so it has no size. - Expecting
alignmentto move a child that has bothleftandrightset. Those values already fix the horizontal position. - Using a positioned child to make the Stack bigger.
- Using
Clip.noneand assuming the overflow area is tappable.
Exercise
A Stack contains a 100 by 60 Container (non-positioned) and a Positioned(top: 0, right: -20, child: Icon(Icons.circle)) with a 24-pixel icon. The Stack uses default settings. What size is the Stack, and how much of the icon is visible?
Show answer
The Stack is 100 by 60. Only the non-positioned Container sets the size, and the positioned icon never contributes. With right: -20, the icon's right edge is 20 pixels beyond the Stack, so 20 of its 24 horizontal pixels lie outside. The default Clip.hardEdge cuts them off, so only about 4 pixels are visible. Setting clipBehavior: Clip.none shows the whole icon, though taps on the outside part still would not reach it.
Exercise
You place Container(color: Colors.red) as the only child of a Stack in a 200 by 100 SizedBox. Nothing red appears. Name two changes that fix it.
Show answer
With default StackFit.loose, the Container has no child and no size, so it shrinks to zero. Either set fit: StackFit.expand on the Stack so the Container gets tight 200 by 100 constraints, or wrap the Container in Positioned.fill. Giving the Container explicit width and height also works.