Alignment with Stack in flutter

Project

Hi, I was trying to align some widgets inside a Stack in Flutter. My end result was something like: enter image description here

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

This will not render as I expected. No matter what I put in the alignment field: Alignment.centerRight and Alignment.centerLeft will always place the child to the center left.

The problem is solved only if I give a fixed width to the wrapping container. Now I understand why this happend but what if I want the container to be the size of his childrens? Label is a dynamic text so his width is unpredictable for me

Any ideas?

Thanks

Upvotes: 15

Views: 34476

Answers (3)

fischja
fischja

Reputation: 71

I ended up wrapping each Stack element with a Row and setting the mainAxisAlignment property:

Stack(
    children: [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            "Center",
          ),
        ],
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text(
            "Right",
          ),
        ],
      ),
    ],
)

Upvotes: 1

awaik
awaik

Reputation: 12335

The more flexible way for such alignment is to wrap Align with Positioned.fill The original answer was posted here 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(),
      ),),
    ],
  ),
);

Upvotes: 22

Khalil Khalil
Khalil Khalil

Reputation: 531

Hy justAnotherOverflowUser,

In your case, you have to use Positioned Widget inside Stack Widget, it will give you what you want.

as example:

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

Upvotes: 27

Related Questions