Flutter中使用Stack和Positioned这两个组件来配合实现绝对定位。Stack允许子组件堆叠,而Positioned用于根据Stack的四个角来确定子组件的位置。
Stack
alignment:
此参数决定如何去对齐没有定位(没有使用Positioned)或部分定位的子组件
textDirection:
和Row、Wrap的textDirection功能一样,都用于确定alignment对齐的参考系
fit:
此参数用于确定没有定位的子组件如何去适应Stack的大小。StackFit.loose表示使用子组件的大小,StackFit.expand表示扩伸到Stack的大小。
overflow:
此属性决定如何显示超出Stack显示空间的子组件;值为Overflow.clip时,超出部分会被剪裁,值为Overflow.visible 时则不会。
Positioned
left、top 、right、 bottom
分别代表离Stack左、上、右、底四边的距离
width和height
用于指定需要定位元素的宽度和高度
**
Positioned的width、height用于配合left、top 、right、 bottom来定位组件
即在水平方向时,你只能指定left、right、width三个属性中的两个,如指定left和width后,right会自动算出(left+width),如果同时指定三个属性则会报错,垂直方向同理
示例
Container(
margin: const EdgeInsets.all(20),
child: Stack(
alignment: Alignment.topLeft,
children: <Widget>[
Positioned(
child: Text("浮生如梦"),
left: 100,
top: 100,
),
Container(
child: Text(
"来也匆匆,去也匆匆",
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlue,
),
Positioned(
child: Text("倚天屠龙记"),
right: 0,
bottom: 100,
),
],
),
width: double.infinity,
height: 300,
),
效果
Stack中添加fit: StackFit.expand,
Container(
margin: const EdgeInsets.all(20),
child: Stack(
alignment: Alignment.topLeft,
fit: StackFit.expand,//没有定位的组件会占满Stack
children: <Widget>[
Positioned(
child: Text("浮生如梦"),
left: 100,
top: 100,
),
Container(
child: Text(
"来也匆匆,去也匆匆",
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlue,
),
Positioned(
child: Text("倚天屠龙记"),
right: 0,
bottom: 100,
),
],
),
width: double.infinity,
height: 300,
),
如图,第二个组件Container占满了Stack全部,并盖住了第一个组件,所以第一个组件不可见。