Alignment with Stack in flutter

jus*_*ser 2 flutter flutter-layout

Project

Hi, I was trying to align some widgets inside a Stack in Flutter. My end result was something like: 在此处输入图片说明

I know that this can be easily achieved with a Row but I want to animate the position ot the two children so I'm forced to use stack.

My problem is simple:

Example code

return Container(
  child: Stack(
    children: <Widget>[
      Align(
        alignment: Alignment.centerLeft,
        child: _buildSign(),
      ),
      Align(
        alignment: Alignment.centerRight,
        child: _buildSign(),
      ),
    ],
  ),
);
Run Code Online (Sandbox Code Playgroud)

这不会像我预期的那样呈现。无论我在alignment场上放什么:Alignment.centerRight并且Alignment.centerLeft总是将孩子放在中间的左边。

仅当我为包装容器提供固定宽度时,问题才得以解决。现在我明白为什么会发生这种情况了,但是如果我希望容器与他孩子的大小一样呢?标签是动态文本,所以他的宽度对我来说是不可预测的

有任何想法吗?

谢谢

awa*_*aik 18

这种对齐的更灵活的方法是用 包装Align原来Positioned.fill 的答案发布在这里Flutter: Bottom center widget in stack

return Container(
  child: Stack(
    children: <Widget>[
      Positioned.fill(
       child: Align(
        alignment: Alignment.centerLeft,
        child: _buildSign(),
      ),),
      Positioned.fill(
       child:Align(
        alignment: Alignment.centerRight,
        child: _buildSign(),
      ),),
    ],
  ),
);
Run Code Online (Sandbox Code Playgroud)


Kha*_*lil 14

Hy justAnotherOverflowUser,

在你的情况下,你必须PositionedStackWidget 中使用Widget,它会给你你想要的。

例如:

Positioned(
  left: 20.0,
  child: Icon(
    Icons.monetization_on, 
    size: 36.0, 
    color: const Color.fromRGBO(218, 165, 32, 1.0)
  )
)
Run Code Online (Sandbox Code Playgroud)