Web 开发者如何理解 Flutter 布局之 —— 6. Stack / Positioned

323 阅读1分钟

《Web 开发者如何理解 Flutter 布局》

本系列旨在帮助 Web 前端开发者更好的理解 Flutter 的布局组件,只做对应的语法映射描述和最基本的技术说明。


堆叠容器和绝对定位。

  • 通过 Stack(堆叠) 创建堆叠容器

  • 通过 Positioned(定位) 创建定位容器

使用 Stack + Positioned 创建带有绝对定位的布局

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

等效于:

  <div
    style=
    "
      position: releative;
    "
  >
    <div
      style=
      "
        position: static;
        width: 300px;
        height: 300px;
        background-color: red;
      "
    >
    </div>
    <div
      style=
      "
        position: absolute;
        width: 300px;
        height: 300px;
        background-color: green;
        top: 50px;
        left: 50px;
        z-index: 1;
      "
    >
    </div>
    <div
      style=
      "
        position: absolute;
        width: 300px;
        height: 300px;
        background-color: blue;
        top: 100px;
        left: 100px;
        z-index: 2;
      "
    >
    </div>
  </div>

在 Stack.children 中, Positioned 在数组的位置越靠后, 则显示的位置越靠前。