In this tutorial, we aim to understand the Stack widget in Flutter. Flutter is a UI toolkit from Google that lets you build natively compiled applications for mobile, web, and desktop from a single codebase. Stack is a built-in widget in Flutter which allows developers to overlap several children widgets in a simple and effective way.
The Stack widget in Flutter allows us to put a number of widgets in the same screen space, and stack them one on top of another. This can be useful for creating complex layouts.
The Stack widget takes an array of children and orders them in a stack, one on top of another. The first widget in the array is at the bottom, and the rest of the widgets are in the order they appear in the array.
There are different ways you can align widgets in a Stack:
* AlignmentDirectional
* Alignment
* FractionalOffset
Creating a Stack layout involves adding the Stack widget and its children to your widget tree. Here's a simple example:
Stack(
alignment: const Alignment(0.6, 0.6),
children: [
CircleAvatar(
backgroundImage: AssetImage('images/pic.jpg'),
radius: 100.0,
),
Container(
decoration: BoxDecoration(
color: Colors.black45,
),
child: Text(
'Flutter',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
],
)
Stack(
alignment: Alignment.center,
children: <Widget>[
Image.network(
'https://your-image-url',
fit: BoxFit.fill,
),
Text(
'Hello Flutter',
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
],
);
In this example, the Image.network
widget is stacked below the Text
widget, thanks to the order in which they are placed inside the children list.
Stack(
children: <Widget>[
Image.network(
'https://your-image-url',
fit: BoxFit.fill,
),
Positioned(
bottom: 50,
right: 50,
child: Text(
'Hello Flutter',
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
),
],
);
In this example, the Positioned
widget is used to position the Text
widget at a specific location in the Stack.
In this tutorial, we learned about the Stack widget in Flutter, how to use it to overlap multiple widgets and create complex UI designs. We also explored different Stack alignments and how to position widgets using the Positioned widget.
Create a simple Stack with an Image and Text widget, where the Text widget is positioned at the center of the Image widget.
Create a Stack with an Image widget and two Text widgets. Use the Positioned widget to position one Text widget at the top left corner and the other one at the bottom right corner of the Image widget.
Create a Stack with an Image widget and three Text widgets. Use the Positioned widget to position each Text widget in different corners of the Image widget.
The solutions to these exercises can be found in the Flutter documentation and various Flutter communities online. Always remember to practice and experiment with different widgets and configurations to become proficient in using Flutter.