craig_ck
craig_ck

Reputation: 77

Using Align widget in the Stack widget without it expanding

I'm trying to create a custom widget and it makes use of the Stack widget. When I wrap the Stack's children using the Positined widget, the stack hugs the children that are not positioned. When I try to use the Align widget for more precise placement the stack expands to fill all the available space.

I'm trying to avoid using any widget with a fixed size, i.e. Container or SizedBox, as the parent for the Stack widget.

Is there a way to prevent the stack from filling all the available space or work around this that archives the same result?

I'm trying to position a child to the top center of the Stack as an example and this is where I am right now:

Using the Positined widget (I have to try multiple time to get the center position and sometimes its still off):

Positioned(
  top: 0,
  left: 80,
  child: child,
);

enter image description here

Using the Align widget:

Align(
  alignment: Alignment.topCenter,
  child: child,
);

enter image description here

This should be the result using the Align widget:

Align(
  alignment: Alignment.topCenter,
  child: child,
);

enter image description here

Upvotes: 1

Views: 513

Answers (1)

eamirho3ein
eamirho3ein

Reputation: 17940

You can set Stack's alignment to topCenter, Try this:

Stack(
    alignment: Alignment.topCenter, // <=== add this
    children: [
      Container(
        color: Colors.grey,
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisSize: MainAxisSize.min, // <=== add this
          children: [
            Container(
              color: Colors.amber,
              height: 30,
              width: 30,
            ),
            Container(
              color: Colors.green,
              height: 30,
              width: 30,
            ),
            Container(
              color: Colors.blue,
              height: 30,
              width: 30,
            ),
            Container(
              color: Colors.yellow,
              height: 30,
              width: 30,
            ),
          ],
        ),
      ),
      Container(
        color: Colors.red,
        height: 30,
        width: 30,
      )
    ],
  )

Note: make sure you set Row's mainAxisSize to min.

enter image description here

Upvotes: 1

Related Questions