Flutter 中的 Stack 小部件:全面指南
在 Flutter 中,Stack
是一个用于叠加多个小部件的布局小部件。它允许你将多个小部件重叠放置,通过控制每个小部件的位置和大小,你可以创建出复杂的布局效果,如徽章图标、对话框、自定义形状等。
基础用法
Stack
最基本的用法是包裹多个小部件,并将它们叠加在一起:
Stack(
children: <Widget>[
Container(color: Colors.red, width: 100.0, height: 100.0),
Container(color: Colors.blue, width: 50.0, height: 50.0),
],
)
在这个例子中,蓝色方块将会叠加在红色方块的上方。
定位子控件
Stack
使用 Positioned
小部件来定位子控件。Positioned
小部件可以指定子控件在 Stack
中的位置和大小:
Stack(
children: <Widget>[
Container(color: Colors.red, width: double.infinity, height: double.infinity),
Positioned(
top: 10.0,
left: 10.0,
child: Container(color: Colors.blue, width: 50.0, height: 50.0),
),
],
)
在这个例子中,蓝色方块将会距离红色方块的左上角 10.0 单位。
使用 fit 属性
Stack
的 fit
属性决定了 Stack
的大小。默认值为 StackFit.loose
,意味着 Stack
的大小将基于其子控件的大小。另一个可选值为 StackFit.expand
,它强制 Stack
占据其父级容器的全部空间:
Stack(
fit: StackFit.expand,
children: <Widget>[
// ... 子控件
],
)
使用 alignment 属性
Stack
的 alignment
属性定义了子控件在 Stack
中的默认对齐方式:
Stack(
alignment: Alignment.center,
children: <Widget>[
Container(color: Colors.red, width: 100.0, height: 100.0),
Container(color: Colors.blue, width: 50.0, height: 50.0),
],
)
在这个例子中,蓝色方块将会在红色方块的中心位置。
实例:徽章图标
使用 Stack
和 Positioned
可以创建一个带有徽章图标的通知气泡:
Stack(
alignment: Alignment.topRight,
children: <Widget>[
Container(
width: 50.0,
height: 50.0,
color: Colors.green,
child: Icon(Icons.add),
),
Positioned(
top: 0.0,
right: 0.0,
child: Container(
padding: EdgeInsets.all(2.0),
color: Colors.red,
child: Text('1'),
),
),
],
)
实例:对话框
使用 Stack
可以创建一个带有阴影和标题的对话框:
Stack(
children: <Widget>[
Container(
padding: EdgeInsets.all(20.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),
boxShadow: [BoxShadow(blurRadius: 10.0)],
),
child: Text('Hello, World!'),
),
Container(
padding: EdgeInsets.all(5.0),
margin: EdgeInsets.only(top: 20.0, right: 20.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
child: Icon(Icons.report_problem),
),
],
)
结语
Stack
是 Flutter 中一个功能强大的布局小部件,它允许你通过叠加和定位小部件来创建复杂的布局效果。掌握 Stack
的使用,可以帮助你创建出既美观又功能丰富的用户界面。