如何布局彼此相邻但重叠的小部件

时间:2020-08-31 00:45:05

标签: flutter layout user-experience

我一直在搞弄Stack,因为Column不允许子窗口小部件重叠。但是,在我看到的每个示例中,可以将小部件彼此相邻放置的每个示例都需要硬编码的宽度和高度。

layout example

在我的布局中,子代的高度取决于子代的内容,而在我的build函数中未知。理想情况下,我想使用Column布置窗口小部件,并在绿色和蓝色容器上使用负的上边距,但这是不允许的。如果我知道每个小部件的渲染高度,则绝对定位它们并不困难,但这似乎是不可能的。

马克·格拉斯伯格(Marc Glasberg)有一个不错的图书馆,名为assorted_layout_widgets,该图书馆有一个ColumnSuper小部件,该小部件允许重叠的列,但适用于所有相同的子级。

对其他人可能拥有的想法感兴趣。

1 个答案:

答案 0 :(得分:1)

您可以尝试的一种方法是使用FractionalTranslation将孩子移动其大小的一小部分。或Transform.translate将孩子移动硬编码距离。这些不需要孩子具有硬编码的大小。

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        FractionalTranslation(
          translation: Offset(0, 0.2),
          child: Container(
            width: 200,
            height: 80,
            color: Colors.red.withOpacity(1),
          ),
        ),
        Container(
          width: 500,
          height: 80,
          color: Colors.greenAccent.withOpacity(0.7),
        ),
        Transform.translate(
          offset: Offset(0, -10),
          child: Container(
            width: 500,
            height: 80,
            color: Colors.deepPurple.withOpacity(0.7),
          ),
        ),
      ],
    );
  }
}

结果:

enter image description here

编辑:

要在绿色框上方放置红色框,我们可以执行以下操作。

  Widget build(BuildContext context) {
    return Column(
      children: [
        FractionalTranslation(
          translation: Offset(0, 1),
          child: Container(
            width: 500,
            height: 80,
            color: Colors.greenAccent.withOpacity(0.7),
          ),
        ),
        FractionalTranslation(
          translation: Offset(0, -0.8),
          child: Container(
            width: 200,
            height: 80,
            color: Colors.red.withOpacity(0.7),
          ),
        ),
        Transform.translate(
          offset: Offset(0, -10),
          child: Container(
            width: 500,
            height: 80,
            color: Colors.deepPurple.withOpacity(0.7),
          ),
        ),
      ],
    );
  }