Flutter——最详细Stack(堆叠布局)使用教程

1.Stack简介:

可以容纳多个组件,以叠加的方式摆放子组件,后者居上。拥有Alignment属性,可以与Positioned组件联合使用,精准并有效摆放。同AndroidFramLayout布局相似。

属性 作用
alignment 子组件摆放的位置
clipBehavior 剪辑小部件的内容
  • 使用场景:

比如开发中需要用户头像上面添加一个特殊标识,就需要是用到堆叠布局;

在这里插入图片描述

创建一个堆叠布局


class CustomStack extends StatelessWidget {
    
    
  @override
  Widget build(BuildContext context) {
    
    
    var yellowBox = Container(
      color: Colors.yellow,
      height: 100,
      width: 100,
    );

    var redBox = Container(
      color: Colors.red,
      height: 90,
      width: 90,
    );

    var greenBox = Container(
      color: Colors.green,
      height: 80,
      width: 80,
    );

    return Container(
      width: 200,
      height: 120,
      color: Colors.grey.withAlpha(33),
      child: Stack(
        textDirection: TextDirection.rtl,
        fit: StackFit.loose,
        alignment: Alignment.topRight,
        children: <Widget>[yellowBox, redBox, greenBox],
      ),
    );
  }
}

在这里插入图片描述

属性Alignment.center

在这里插入图片描述

属性Alignment.bottomLeft

在这里插入图片描述

2.组件Positioned

精准堆叠布局内部,子组件的位置与排列;

属性 作用
left 向左距离
top 向上距离
right 向右距离
bottom 向下距离
Stack(
        textDirection: TextDirection.rtl,
        fit: StackFit.loose,
        alignment: Alignment.bottomLeft,
        children: <Widget>[
          yellowBox,
          redBox,
          Positioned(
            bottom: 10,
            right: -30,
            child: greenBox,
          )
        ],
      )

在这里插入图片描述

可以看到绿色组件有一部分被裁剪调了,是因为没有使用clipBehavior属性,接下来我们来看Clip.none属性效果

属性clipBehavior: Clip.none

Stack(
        textDirection: TextDirection.rtl,
        fit: StackFit.loose,
        alignment: Alignment.bottomLeft,
        clipBehavior: Clip.none,
        children: <Widget>[
          yellowBox,
          redBox,
          Positioned(
            bottom: 10,
            right: -30,
            child: greenBox,
          )
        ],
      ),

加上该属性之后我们可以看到,绿色组件超出的部分也显示出来了。该属性的意义也就一目了然。

3.组件Align

精准控制子组件的位置,同Positioned相似。

创建一个带Align组件的样式

Stack(
        textDirection: TextDirection.rtl,
        fit: StackFit.loose,
        alignment: Alignment.bottomLeft,
        clipBehavior: Clip.none,
        children: <Widget>[
          Align(
            alignment: const Alignment(0, 0),
            child: redBox,
          ),
        ],
      )

在这里插入图片描述

可以看到该布局显示再正中间,Alignment(0, 0) 该属性分为 x 轴跟 y轴,范围值都是 -11 之间;

看Alignment(0, 1)
在这里插入图片描述

可以看到当y等于1时,红色组件排列再最底部;

看 Alignment(-0.5, -0.5)
在这里插入图片描述

当x等于 -0.5 时,很明显组件位于横轴-1到0的中间;
当y等于 -0.5 时,很明显组件位于主轴-1到0的中间;
总结x值的大小是根据横轴排列,y值的大小是根据主轴排列;

属性 Alignment(1, 4)
在这里插入图片描述

当x与y大于1时,子组件并没有被裁剪。说明使用Align属性并不受clipBehavior: Clip.none影响;

猜你喜欢

转载自blog.csdn.net/u013290250/article/details/121751397