Stack Widget in Flutter
The Stack widget is a very powerful layout widget in Flutter that allows you to stack widgets on top of each other. You can position each widget within the stack using absolute or relative coordinates. This allows you to create complex user interfaces that would be difficult to achieve with other layout widgets.
In this article, we'll take a closer look at the Stack widget, how it works, and some examples of how you can use it in your Flutter apps.
Example Code:
Stack(
alignment: Alignment.center,
children: [
Container(
color: Colors.blue,
width: 200,
height: 200,
),
Positioned(
left: 50,
top: 50,
child: Container(
color: Colors.red,
width: 100,
height: 100,
),
),
Positioned(
right: 50,
bottom: 50,
child: Container(
color: Colors.green,
width: 100,
height: 100,
),
),
],
);
Properties:
- alignment (required): Determines how the children are positioned within the Stack.
- children (required): A list of Widgets that will be stacked on top of each other.
- fit (optional): Determines how non-positioned children should be sized within the Stack.
- overflow (optional): Determines how overflow from the children is handled.
..
Another example:
Learn how to use the Stack widget in Flutter to create an ImageCard widget that displays an image with a title and a favorite icon.
import 'package:flutter/material.dart';
class ImageCard extends StatelessWidget {
const ImageCard({super.key});
@override
Widget build(BuildContext context) {
return Stack(
children: [
// This Card widget provides a rounded rectangle shape and elevation to the Container.
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
elevation: 5,
child: Container(
// This Container is used to set the size and decoration of the Card.
width: double.infinity,
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: const DecorationImage(
image: AssetImage('assets/images/bg.webp'),
fit: BoxFit.cover,
),
),
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// This SizedBox is used to create space at the bottom of the image.
SizedBox(height: 160),
Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Image Title',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
],
),
),
),
// This Positioned widget is used to position the heart icon on the top right of the Card.
const Positioned(
top: 16,
right: 16,
child: Icon(
Icons.favorite,
color: Colors.red,
),
),
],
);
}
}
..
Comments
Post a Comment