Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 73 ยท Layout

Stack, Align and Positioned

Layer widgets in Flutter with Stack, place them with Align and Positioned, size them with FractionallySizedBox, and learn how clipping and hit testing work.

Row and Column put widgets next to each other. Sometimes you want them on top of each other: a badge on an icon, text over a photo, a floating button above a list, a loading spinner covering a form. For layering, Flutter gives you Stack, and for placing a single child inside a space, Align.

This lesson explains how a Stack sizes itself, how Positioned and Alignment work, what FractionallySizedBox is for, and why a child that sticks out of a Stack may be clipped and may not respond to taps. It continues from Row, Column, Expanded and Flexible and uses the constraint rule from Constraints go down, sizes go up.

Real vs stand-in. Stack, Positioned, Align and FractionallySizedBox are real Flutter widgets, and the Dart snippets are read-only. The live examples are JavaScript stand-ins that use the same arithmetic for alignment and positioning.

Layering tools

Stack Paints children in order, first at the back.
Align Places one child inside its space.
Positioned Pins a child to edges of a Stack.
FractionallySizedBox Sizes a child as a share of its parent.
1 / 2

Stack basics

A Stack paints its children in list order: the first child is at the back, the last is on top.

DART
Stack(
  children: [
    Container(width: 200, height: 200, color: Colors.indigo),
    Container(width: 120, height: 120, color: Colors.teal),
    const Text('On top', style: TextStyle(color: Colors.white)),
  ],
)

How big is a Stack? It looks at its non-positioned children (those that are not wrapped in Positioned), lays them out with loose constraints, and becomes as large as the biggest one. In the example above that is 200 by 200. If a Stack has only positioned children, it takes the biggest size its parent allows, so wrap it in a SizedBox when you want a specific size.

Two properties shape the stack:

  • alignment places the non-positioned children inside the stack. The default is the top-start corner, so the smaller teal box and the text sit at the top left. Use Alignment.center to center them.
  • fit: StackFit.expand forces every non-positioned child to fill the stack (tight constraints), which is handy for a background image or a full-screen overlay. The default StackFit.loose lets children keep their own size.

Align and alignment values

Align is the one-child version of the same idea. It fills the space its parent gives it (unless you set widthFactor or heightFactor), passes loose constraints to its child, and places the child by an Alignment.

An Alignment is a pair of numbers from -1 to 1. (-1, -1) is the top-left corner, (0, 0) the center and (1, 1) the bottom-right. The child's top-left corner lands at:

TEXT
x = (parentWidth  - childWidth)  * (alignX + 1) / 2
y = (parentHeight - childHeight) * (alignY + 1) / 2
DART
Align(
  alignment: Alignment.bottomRight,   // Alignment(1, 1)
  child: FloatingActionButton(onPressed: add, child: const Icon(Icons.add)),
)

Center is simply Align with Alignment.center. For right-to-left languages, AlignmentDirectional.topStart flips automatically; Stack uses it by default, which is good for internationalization (see Accessibility and Internationalization).

Positioned

Inside a Stack, wrap a child in Positioned to pin it to edges. You give distances from the stack's edges with left, top, right, bottom, and optionally width and height. You must not over-constrain an axis: horizontally, use at most two of left, right and width.

DART
SizedBox(
  width: 300,
  height: 200,
  child: Stack(
    children: [
      Positioned.fill(child: Image.asset('assets/photo.jpg', fit: BoxFit.cover)),
      Positioned(left: 12, bottom: 12, right: 12,
        child: Text('Sunset at the lake', style: TextStyle(color: Colors.white))),
      Positioned(top: 8, right: 8, child: Icon(Icons.favorite, color: Colors.red)),
    ],
  ),
)

Positioned.fill is a shortcut for all four distances at zero. Giving both left and right makes the child as wide as the space between them, so the caption above stretches across the photo with 12 px margins. A Positioned widget can only be a direct child of a Stack; anywhere else you get the error Incorrect use of ParentDataWidget.

Working out positions

This stand-in resolves a Stack child's rectangle from either Alignment or Positioned values, with the same formulas as the framework.

JS Alignment and Positioned arithmetic

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For instance, Positioned(top: 8, right: 8) with a 40 px wide badge in a 300 px stack puts the badge's left edge at 300 - 8 - 40 = 252.

FractionallySizedBox

Sometimes a size should be a share of the available space rather than a fixed number of pixels: a progress bar that is 60 percent full, a hero image that fills half the width. FractionallySizedBox multiplies the incoming maximum constraints by widthFactor and heightFactor and tightens the child to that size. It also aligns the child with its alignment (default center).

DART
FractionallySizedBox(
  widthFactor: 0.6,
  alignment: Alignment.centerLeft,
  child: Container(height: 8, color: Colors.green),   // 60% of the parent's width
)

The factors apply to the constraints, not to the screen, so the box needs a bounded parent: inside an unbounded Row or scroll view, a fraction of infinity is still infinity and layout fails. It is a good fit with Align for progress bars, and with LayoutBuilder for sizing against the real available space, see Responsive and adaptive layouts.

JS A share of the parent's constraints

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Clipping and hit testing

A Stack clips its children to its own bounds by default (clipBehavior: Clip.hardEdge). A badge that sticks out of the stack is cut off. Two ways to fix that: make the stack big enough to contain the badge (for example wrap the icon in a SizedBox that includes space for the badge), or set clipBehavior: Clip.none.

DART
Stack(
  clipBehavior: Clip.none,
  children: [
    const Icon(Icons.notifications, size: 32),
    Positioned(right: -6, top: -6, child: Badge(label: Text('3'))),
  ],
)

With Clip.none the badge draws outside the box, but there is a catch: hit testing still follows the render object's bounds. A tap on the part of the badge that sticks out may not reach it, because the pointer is outside the stack and the stack never asks its children. If a protruding child must be tappable, enlarge the stack so the child is inside it.

Also remember that later children cover earlier ones. An invisible, full-size widget on top of a Stack will absorb taps; wrap decorative overlays in IgnorePointer so touches pass through to what is below. Gestures and Input Handling explains hit testing in detail.

SafeArea, Flex, Tooltip and feedback widgets

A few small widgets from the Layout and Material families complete the toolbox.

SafeArea

Phones have notches, rounded corners, status bars and gesture bars. SafeArea adds padding so content stays clear of them:

DART
Scaffold(
  body: SafeArea(
    minimum: const EdgeInsets.all(8),   // at least this much, even where there is no inset
    child: const Text('Always readable'),
  ),
)

It reads MediaQuery.paddingOf(context). Disable a side with top: false or bottom: false when a widget (such as an image header) should bleed under it. A Scaffold with an AppBar already handles the top, so you mostly need SafeArea for screens without an app bar, bottom sheets and edge-to-edge layouts. In a scrolling list use SliverSafeArea. The keyboard is not part of this padding: it is MediaQuery.viewInsetsOf(context), and a Scaffold shrinks its body for it by default.

JS Insets: notch, bars and keyboard

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Flex

Row and Column are both Flex widgets with a fixed direction. Use Flex itself when the direction is decided at run time, for example a toolbar that is horizontal on a wide screen and vertical on a narrow one, with the same children and Expanded rules (Row, Column, Expanded and Flexible):

DART
Flex(
  direction: isWide ? Axis.horizontal : Axis.vertical,
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: const [Expanded(child: Text('Left')), Expanded(child: Text('Right'))],
)

Tooltip

A Tooltip shows a short label on long-press (mobile) or hover (desktop and web) and is announced by screen readers. Most IconButtons should have one through the tooltip property:

DART
IconButton(icon: const Icon(Icons.share), tooltip: 'Share', onPressed: _share)

Tooltip(
  message: 'Last synced 2 minutes ago',
  waitDuration: const Duration(milliseconds: 500),
  triggerMode: TooltipTriggerMode.tap,      // also show on tap
  preferBelow: false,
  child: const Icon(Icons.cloud_done),
)

MaterialBanner and other feedback

A SnackBar fades after a few seconds and suits "Saved". A MaterialBanner stays until dismissed and suits a persistent message such as "You are offline". It needs at least one action:

DART
ScaffoldMessenger.of(context).showMaterialBanner(
  MaterialBanner(
    content: const Text('You are offline. Changes will sync later.'),
    leading: const Icon(Icons.wifi_off),
    actions: [
      TextButton(
        onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
        child: const Text('Dismiss'),
      ),
    ],
  ),
);

Show it when the state changes (a connectivity stream) and hide it when the state recovers. Banners, snack bars and dialogs are compared in Material 3 widgets.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a Stack, which child is painted on top?

    Children paint in list order, so the last one is on top.
  2. 2. What is the position of a child with Alignment(1, -1)?

    x = 1 is the right edge and y = -1 is the top edge, so the child sits in the top-right corner.
  3. 3. Where must a Positioned widget be placed?

    Positioned writes parent data that only Stack understands. Elsewhere Flutter throws an Incorrect use of ParentDataWidget error.
  4. 4. A notification badge hangs outside the corner of its Stack and is cut off. What can you do?

    Stack clips to its bounds by default. Clip.none stops the clipping, but for taps the child should be inside the Stack's bounds.
  5. 5. What does FractionallySizedBox(widthFactor: 0.5) do?

    It multiplies the incoming maximum constraints by the factor, so it depends on the parent, and needs a bounded parent.

Summary

  • Stack layers children (first at the back); it sizes to its biggest non-positioned child.
  • Align places one child with an Alignment from (-1, -1) to (1, 1); Center is Align at (0, 0).
  • Positioned pins a direct child of a Stack with edge distances; Positioned.fill covers it all.
  • FractionallySizedBox sizes a child as a fraction of the parent's constraints.
  • Stacks clip by default and hit testing follows the bounds; use Clip.none carefully and IgnorePointer for overlays.

Next: Padding, SizedBox, Container and ConstrainedBox