Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Sometimes I want to force a widget to take a specific size, which I usually do by using a SizedBox/ConstrainedBox/Container

But I've realized that in some situations, the widget merely ignores it and takes a different size. Why is that?

Example:

Expected behavior:

enter image description here

Actual behavior:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

This situation happens when the parent and its child wants two different sizes; but the parent has no idea how it should align its child within its boundaries.

The following code doesn't give enough information to tell how to align the red box within the blue box:

Container(
  color: Colors.blue,
  width: 42,
  height: 42,
  child: Container(
    color: Colors.red,
    width: 24,
    height: 24,
  ),
),

So while it could be centered as such:

enter image description here

it would also be perfectly reasonable to expect the following alignment instead:

enter image description here


In that situation, since Flutter doesn't know how to align the red box, it will go with an easier solution:

Don't align the red box, and force it to take all the available space; which leads to:

enter image description here


To solve this issue, the solution is to explicitly tell Flutter how to align the child within its parent boundaries.

The most common solution is by wrapping the child into an Align widget:

Container(
  color: Colors.blue,
  width: 42,
  height: 42,
  child: Align(
    alignment: Alignment.center,
    child: Container(
      color: Colors.red,
      width: 24,
      height: 24,
    ),
  ),
),

Some widgets such as Container or Stack will also offer an alignment property to achieve similar behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...