【问题标题】:How to layout widgets adjacent to each other, but with overlap如何布局彼此相邻但重叠的小部件
【发布时间】:2020-12-19 03:21:04
【问题描述】:

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

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

Marc Glasberg 有一个不错的库,名为 assorted_layout_widgets,它有一个 ColumnSuper 小部件,允许重叠列,但它同样适用于所有子级。

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

【问题讨论】:

    标签: flutter layout user-experience


    【解决方案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),
              ),
            ),
          ],
        );
      }
    }
    

    结果:

    编辑:

    要让绿色盒子上的红色盒子,我们可以做这样的事情。

      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),
              ),
            ),
          ],
        );
      }
    

    【讨论】:

    • 这与我想要达到的目标非常接近,我接受这个答案。但是,红色框应该在绿色框的顶部,我看不出有任何方法可以通过翻译其他孩子来实现。
    • 可以做到这一点的一种方法是颠倒绿色和红色框的顺序,然后使用翻译相应地移动它们。我将编辑答案以包含这部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2020-07-03
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多