Flutter层叠布局 Stack、Positioned

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全部,并盖住了第一个组件,所以第一个组件不可见。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值