Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Constraints not constraining widget (explanation needed)

Tags:

flutter

dart

class Test extends StatelessWidget {
  Widget build(BuildContext context) {
    return UnconstrainedBox(
        child: Container(
            height: 250.0,
            width: 250.0,
            decoration:
                BoxDecoration(shape: BoxShape.circle, color: Colors.red),
            child: Opacity(
                opacity: 0.5,
                child: Container( // WIDGET IN QUESTION
                    constraints:
                        BoxConstraints.expand(width: 50.0, height: 50.0),
                    color: Colors.yellow))));
  }
}

According to the Container class documentation...

If the widget has no child and no alignment, but a height, width, or constraints are provided, then the Container tries to be as small as possible given the combination of those constraints and the parent's constraints.

Instead, the widget is trying to be as large as possible (size of parent) rather than 50x50. I understand that I can use something like UnconstrainedBox, but I'm looking for an explanation of this behavior.

Looking for: looking-for

Currently getting: currently-getting

like image 479
M. Walker Avatar asked Sep 19 '18 22:09

M. Walker


People also ask

How do you use constraints in Flutter?

A constraint is just a set of 4 doubles: a minimum and maximum width, and a minimum and maximum height. Then the widget goes through its own list of children. One by one, the widget tells its children what their constraints are (which can be different for each child), and then asks each child what size it wants to be.

How do I show widgets based on condition in Flutter?

It is very simple using conditional operators: build(context) => condition ? MaterialButton(...) : Container(); In this case, condition is a boolean expression (returning bool , same thing you would put into an if-statement) and the empty Container will render as empty space and will not take up any space.

When a column is in a parent that does not provide a finite height constraint?

RenderFlex children have non-zero flex but incoming height constraints are unbounded. When a column is in a parent that does not provide a finite height constraint, for example if it is in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis.


Video Answer


1 Answers

The problem is your root Container.

By setting a width+height without an alignment, Container forces its child to fill the available space.

If you want that child take the least amount of space, you need to specify your root container how it should align its child within its bounds.

Container(
  width: 250,
  height: 250,
  alignment: Alignment.center,
  child: Whatever(),
);
like image 68
Rémi Rousselet Avatar answered Oct 21 '22 07:10

Rémi Rousselet