What is Stack in Flutter: Explanation and Example
Stack is a widget that lets you place widgets on top of each other like layers. It works like a stack of papers where the last widget added appears on top, allowing you to overlap or position widgets freely.How It Works
The Stack widget in Flutter arranges its child widgets in a way that they can overlap each other. Imagine a stack of books or papers on a table: the first one you put down is at the bottom, and each new one goes on top. Similarly, in a Stack, the first child is at the bottom and the last child is on top.
This allows you to create complex layouts where widgets can be layered, such as placing text over an image or adding buttons on top of other content. You can control the position of each child inside the stack using the Positioned widget, which lets you specify exact coordinates or edges.
Example
This example shows a red square with a smaller blue square positioned on top in the bottom right corner.
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: Stack( children: [ Container(width: 200, height: 200, color: Colors.red), Positioned( bottom: 0, right: 0, child: Container(width: 100, height: 100, color: Colors.blue), ), ], ), ), ), ); } }
When to Use
Use Stack when you want to overlap widgets or position them relative to the edges of a container. It is useful for:
- Adding badges or icons on top of images.
- Creating custom buttons with layered effects.
- Building complex UI elements like cards with overlapping decorations.
- Positioning widgets freely without affecting the layout of others.
For example, in a chat app, you might use Stack to place a small online status dot over a user avatar.
Key Points
- Stack arranges children in layers, with the last child on top.
- Use
Positionedto place children at specific positions inside the stack. - Without
Positioned, children are placed at the top-left corner by default. - Stack is great for overlapping and free positioning but not for linear layouts.