记录

记录Flutter开发中布局部分的关键信息

# Stack组件 在界面的Z轴 就是垂直于屏幕的部分布局。

Stack 是一个可以叠加多个子组件的布局组件。默认情况下,子组件会从左上角开始堆叠,后添加的子组件会覆盖在前面的子组件之上。

# Row 
# Center
# Column
。。。

Positioned 是一个用于在 Stack 布局中精确控制子组件位置的组件。它允许你指定子组件相对于父容器(通常是 Stack)的偏移量或位置。理解 Positioned 的关键在于理解 Stack 的布局机制以及 Positioned 的定位方式。


1. Stack 布局

Stack 是一个可以叠加多个子组件的布局组件。默认情况下,子组件会从左上角开始堆叠,后添加的子组件会覆盖在前面的子组件之上。

Stack(
  children: [
    Container(color: Colors.red, width: 100, height: 100),
    Container(color: Colors.blue, width: 80, height: 80),
  ],
)

在上面的例子中,蓝色的 Container 会覆盖在红色的 Container 之上。


2. Positioned 的作用

Positioned 用于在 Stack 中精确控制子组件的位置。它可以指定子组件的 上、下、左、右 四个方向的偏移量,或者直接指定 宽高


3. Positioned 的属性

Positioned 的主要属性如下:

属性 描述
left 子组件距离父容器左边的距离。
right 子组件距离父容器右边的距离。
top 子组件距离父容器顶部的距离。
bottom 子组件距离父容器底部的距离。
width 子组件的宽度(可选)。
height 子组件的高度(可选)。

4. Positioned 的使用规则


5. 示例代码

以下是一些常见的 Positioned 使用场景:

示例 1:指定 lefttop

Stack(
  children: [
    Positioned(
      left: 50,
      top: 50,
      child: Container(color: Colors.blue, width: 100, height: 100),
    ),
  ],
)

在这个例子中,蓝色的 Container 会距离父容器的左边 50 像素,距离顶部 50 像素。

示例 2:指定 rightbottom

Stack(
  children: [
    Positioned(
      right: 20,
      bottom: 20,
      child: Container(color: Colors.green, width: 100, height: 100),
    ),
  ],
)

在这个例子中,绿色的 Container 会距离父容器的右边 20 像素,距离底部 20 像素。

示例 3:指定 leftrighttopbottom

Stack(
  children: [
    Positioned(
      left: 20,
      right: 20,
      top: 20,
      bottom: 20,
      child: Container(color: Colors.yellow),
    ),
  ],
)

在这个例子中,黄色的 Container 会距离父容器的四边各 20 像素,宽度和高度会根据父容器的大小自动调整。

示例 4:未指定位置

Stack(
  children: [
    Positioned(
      child: Container(color: Colors.purple, width: 100, height: 100),
    ),
  ],
)

在这个例子中,紫色的 Container 会默认位于 Stack 的左上角。


6. 注意事项


总结

PositionedStack 布局中用于精确控制子组件位置的重要工具。通过 leftrighttopbottom 等属性,你可以轻松实现复杂的布局需求。结合 Stack 的叠加特性,Positioned 在 Flutter 的 UI 开发中非常常用。 😊