Flutter Stack
The Stack
widget is used to overlap widgets and position them on top of each other. Whatever widget you add first to the stack will be at the bottom and later added widgets will be on top.
Syntax
Stack(
alignment: AlignmentDirectional.center,
children: <Widget>[ /* List of Widget */ ]
)
Example
Stack(
alignment: AlignmentDirectional.center,
children: <Widget>[
Container(
child: Text("Bottom Widget"),
color: Colors.green,
width: 200,
height: 200,
),
Container(
child: Text("Top Widget"),
color: Colors.red,
width: 100,
height: 100,
),
],
)
Output
Explanation
In the above example, we have used two containers as children of the Stack
widget. The first container represents the bottom widget, while the second container represents the top widget. The alignment property is used to align the widgets in the center of the stack.
Use
The Stack
widget is mostly used for designing custom layouts, and it is also useful while creating chat applications and photo editing applications where you need to overlap widgets.
Important Points
Whenever you use
Stack
, always make sure to provide an alignment property because it's a mandatory property and otherwise it will throw an error.Every added widget to
Stack
widget has its own position and size.You can add as many child widgets as you need, but be careful while using it as it may impact the performance.
Summary
In this tutorial, we learned about the Stack
widget in Flutter. We covered the syntax, explains a simple example, its output, the importance of providing alignment property, and how it can be useful in app development.