The Stack widget in Flutter lets you layer multiple widgets on top of each other, positioning them relative to the stack's boundaries or other widgets within it. It's like stacking books: the first widget is at the bottom, and the last one is on top. This allows you to overlap widgets on a single screen, rendering them from bottom to top.
By default, the first widget in the stack has the maximum size compared to the others.
In a stack, child widgets can be either positioned or non-positioned.
Positioned items are wrapped in the Positioned widget and must have at least one non-null property.
Non-positioned child widgets align themselves based on the stack's alignment, with the default position being the top-left corner. You can use the alignment attribute to change this.
Constructors
Stack class
Stack(
{Key key,
AlignmentGeometry alignment: AlignmentDirectional.topStart,
TextDirection textDirection,
StackFit fit: StackFit.loose,
Overflow overflow: Overflow.clip,
Clip clipBehavior: Clip.hardEdge,
List<Widget> children: const <Widget>[]}
)
Positioned Class
Properties of Flutter Stack & Positioned widget
alignment
This property, which takes a parameter of AlignmentGeometry, controls how a non-positioned or partially-positioned child widget will align within the Stack. It determines the position of children widgets in the stack, offering options like top, bottom, center, and center-right.
Stack(
alignment: Alignment.center
),
fit
textDirection
overflow
clipBehavior
Practice with Stack widget
Stack & Positioned Example 1
class StackExample1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff3555c0),
leading: SvgPicture.asset(
'assets/image/code_capp1.svg',
fit: BoxFit.fitWidth,
),
//remove this line
title: Text('Code Cappuccino', style: TextStyle(color: Colors.white)),
),
body: Center(
child: Stack(
alignment: Alignment.center,
children: [
// Bottom-most widget
Container(
color: Colors.teal,
width: 400,
height: 400,
child: Text(
'Teal',
style: TextStyle(color: Colors.white,
fontSize: 20),
),
),
// Middle widget
Positioned(
top: 50,
left: 50,
child: Container(
color: Colors.red,
width: 200,
height: 200,
child: Text(
'Red',
style: TextStyle(color: Colors.white,
fontSize: 20),
),
),
),
// Top-most widget
Positioned(
bottom: 50,
right: 50,
child: Container(
color: Colors.amber,
width: 200,
height: 200,
child: Text(
'Yellow',
style: TextStyle(color: Colors.white,
fontSize: 20),
),
),
),
// Text widget
Positioned(
bottom: 15,
child: Text(
'Stack Widget',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
),
);
}
}
Comments