Sub topic 10
Layering widgets with Stack
This chapter assumes you can write a StatelessWidget, read Dart named parameters, and run a Flutter app. It also assumes you know the rule from earlier chapters: a parent passes constraints down, and the child picks a size within them and passes it back up.
Row and Column place children side by side along one axis. They never let children overlap. A Stack does the opposite. It paints its children in the same area, one on top of another. You use it for badges on avatars, text over images, floating buttons, and loading overlays.
What a Stack does
A Stack lays out its children in a shared coordinate space. The origin is the top-left corner of the Stack (top-right in right-to-left languages). Children are painted in list order. The first child is at the bottom, and the last child is on top.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: StackDemo()))));
class StackDemo extends StatelessWidget {
const StackDemo({super.key});
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.center,
children: [
Container(width: 120, height: 120, color: Colors.blue),
const Text('Hi'),
],
);
}
}The blue square is painted first. The Text is painted second, so it appears on top. The alignment property centers the text inside the Stack. Without it, the text would sit in the top-left corner.
Reversing the order of the two children would hide the text behind the square. Paint order is the only way a Stack decides what is in front. There is no z-index property.
Two kinds of children
A Stack treats its children differently depending on whether they are positioned.
- A non-positioned child is any widget that is not a
Positioned. The Stack gives it loose constraints and places it using the Stack'salignment. - A positioned child is a
Positionedwidget. The Stack places it using the offsets you give (left,top,right,bottom), and ignoresalignmentfor it.
You can mix both kinds in one Stack. Most real layouts do.
The diagram below summarizes how the Stack handles each child.
Placing children with Positioned
Positioned is a widget that only works as a direct child of a Stack. It measures distances from the Stack's edges.
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),
),
],
),
)Positioned.fill sets left, top, right, and bottom all to 0, so the grey box stretches to the full Stack. The second Positioned pins the icon 8 logical pixels from the right edge and 8 from the bottom edge.
The rules for the four offsets:
| You set | Result |
|---|---|
| `left` and `top` only | The child keeps its own size and sits at that point. |
| `left` and `right` | The child's width is forced to `Stack width - left - right`. |
| `top` and `bottom` | The child's height is forced to `Stack height - top - bottom`. |
| `width` with `left` (or `right`) | The child gets that exact width. |
| Only `left`, `right`, and `width` all set | An error. A dimension can be fixed by at most two of its three values. |
A positioned child that has no offset on an axis is placed at the start of that axis (left or top). Setting just bottom: 8 leaves left unset, so the child sits at the left edge.
For a Stack with a known size, Positioned is precise. When the size is not known in advance, consider Align as a Stack child. It positions a child by fractional alignment rather than by pixel offsets.
How a Stack sizes itself
A Stack has to decide its own size before it can place anything. It follows these rules:
- It lays out all non-positioned children with loose constraints (minimum 0, maximum equal to the Stack's own maximum, by default).
- If there is at least one non-positioned child, the Stack becomes as large as the biggest one, within its constraints.
- If every child is positioned, there is nothing to measure. The Stack then expands to the largest size its constraints allow.
- Positioned children never affect the Stack's size.
This explains a common surprise. Suppose you build a Stack with only Positioned children inside a Column. The Column gives it unbounded height, so the Stack cannot expand to "the biggest allowed size", and you get an unbounded-height error. The fix is to give the Stack a size, for example with a SizedBox, or to include one non-positioned child that sets the size.
The fit property changes how non-positioned children are constrained.
| `fit` value | Effect on non-positioned children |
|---|---|
| `StackFit.loose` (default) | Constraints are loosened. Children may be smaller than the Stack. |
| `StackFit.expand` | Children are forced to the Stack's biggest size. |
| `StackFit.passthrough` | The Stack's own incoming constraints are passed to the children unchanged. |
Use StackFit.expand when a background child should fill the whole Stack without wrapping it in Positioned.fill.
Alignment
The alignment property takes an AlignmentGeometry. Common values are Alignment.topLeft, Alignment.center, and Alignment.bottomRight. You can also write fractions, where Alignment(-1, -1) is the top-left corner, Alignment(0, 0) is the center, and Alignment(1, 1) is the bottom-right corner.
The default is AlignmentDirectional.topStart. That respects text direction, so in a right-to-left locale the default corner is the top right. If you want a fixed corner regardless of language, use Alignment.topLeft.
Clipping
By default, Stack uses clipBehavior: Clip.hardEdge. A child that extends beyond the Stack's bounds is cut off. This often surprises people who place a badge with a negative offset such as Positioned(top: -8, right: -8, ...). The part outside the Stack disappears.
You have two options.
- Set
clipBehavior: Clip.noneso children can paint outside the Stack's bounds. - Make the Stack large enough to contain the badge.
Stack(
clipBehavior: Clip.none,
children: [
const CircleAvatar(radius: 28, child: Icon(Icons.person)),
Positioned(
top: -4,
right: -4,
child: Container(
padding: const EdgeInsets.all(4),
decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
child: const Text('3', style: TextStyle(color: Colors.white, fontSize: 12)),
),
),
],
)With Clip.none, the badge overlaps the avatar's corner and is painted fully.
Be aware of one limit. A child that paints outside the Stack's bounds is visible, but it does not receive taps there. Hit testing checks the child against the Stack's bounds first, so touches outside the Stack never reach it.
Common mistakes
- Stack with only Positioned children in unbounded space. Give the Stack a fixed size or a non-positioned child.
- Positioned outside a Stack.
Positionedplaced under aRow,Container, orPaddingthat sits between it and the Stack throws "Incorrect use of ParentDataWidget". Positioned must be a direct child. - Overlays that block touches. A full-size child on top of the Stack receives taps first. Wrap decorative overlays in
IgnorePointerso touches pass through to the widgets underneath. - Expecting a z-index. To bring a widget forward, move it later in the
childrenlist.
Exercise
A Stack contains one Container of 100 by 100 and a Positioned(left: 10, right: 10, top: 0, child: Container(height: 20, color: Colors.red)). How wide is the red container, and how large is the Stack?
Show answer
The Stack is 100 by 100, because the only non-positioned child sets its size and positioned children never change it. The red container is forced to a width of 100 - 10 - 10 = 80, and its height is its own 20.
Exercise
You place a notification badge with Positioned(top: -8, right: -8, ...) on an avatar. The badge is cut off, and after fixing the clipping its corner still ignores taps. What two things explain this, and what is one fix that solves both?
Show answer
The Stack clips with Clip.hardEdge by default, so the part outside its bounds is cut. Even with Clip.none, hit testing ignores touches outside the Stack's bounds. A fix for both is to enlarge the Stack, for example by wrapping the avatar in Padding of 8 inside the Stack, and use positive offsets so the badge lies inside the bounds.