1.Flutter Stack组件
Stack表示堆的意思,我们可以用Stack或者Stack结合Align或者Stack结合 Positiond来实现页面的定位布局
属性 | 说明 |
alignment | 配置所有子元素的显示位置 |
children | 子组件 |
只使用Stack组件的情况下,所有的组件都是重叠在一起的,具体见下:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return Stack(
children: [
Container(
height: 400,
width: 300,
color: Colors.red,
),
Container(
height: 200,
width: 200,
color: Colors.yellow,
),
const Text("我们是重叠在一起的")
],
);
}
}
2.Positioned相对定位组件
Stack组件中结合Positioned组件也可以控制每个子元素的显示位置.
注意事项:
在使用Positioned组件的时候,必须在Positioned中为该容器设置宽度和高度.如果Positioned设置了宽度和高度,那么子组件设置宽高以后将无效.
属性 | 说明 |
top | 子元素距离顶部的距离 |
bottom | 子元素距离底部的距离 |
left | 子元素距离左侧距离 |
right | 子元素距离右侧距离 |
child | 子组件 |
width | 组件的高度 (注意:宽度和高度必须是固定值,没法使用double.infifinity),只能使用final size =MediaQuery.of(context).size; 方法 |
height | 子组件的高度 |
示例:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return Container(
width: 300,
height: 400,
color: Colors.red,
child: Stack(
children: [
//Positioned的组件是相对于这个Stack组件外层这个组件的.如果这个Stack组件写到我们这个根组件里面,那它这个时候就相对于我们整个屏幕,如果这个Stack组件配置到我们Container组件里面的话,那这个时候就相对于我们Container组件的位置进行定位的.
Positioned(
left: 0,//left和bottom是配置黄色Container相对于红色Container的位置
bottom: 0,
child: Container(
height: 200,
width: 200,
color: Colors.yellow,
)),
const Text("你好flutter")//如果需要设置Text组件的相对位置,也需要在外层包裹一层Positioned组件.
],
),
);
}
}