Dealing with box constraints

In Flutter, widgets are rendered by their underlying RenderBox objects. Render boxes are given constraints by their parent, and size themselves within those constraints. Constraints consist of minimum and maximum widths and heights; sizes consist of a specific width and height.

Generally, there are three kinds of boxes, in terms of how they handle their constraints:.

Some widgets, for example Container, vary from type to type based on their constructor arguments. In the case of Container, it defaults to trying to be as big as possible, but if you give it a width, for instance, it tries to honor that and be that particular size. Others, for example Row and Column (flex boxes) vary based on the constraints they are given, as described below in the “Flex” section.

Unbounded constraints

  • In certain situations, the constraint that is given to a box is unbounded, or infinite. This means that either the maximum width or the maximum height is set to double.INFINITY.
  • A box that tries to be as big as possible won’t function usefully when given an unbounded constraint and, in debug mode, such a combination throws an exception that points to this file.
  • The most common cases where a render box finds itself with unbounded constraints are within flex boxes (Row and Column), and within scrollable regions (ListView and other ScrollView subclasses).
  • In particular, ListView tries to expand to fit the space available in its cross-direction (for example, if it’s a vertically-scrolling block, it tries to be as wide as its parent). If you nest a vertically scrolling ListView inside a horizontally scrolling ListView, the inner one tries to be as wide as possible, which is infinitely wide, since the outer one is scrollable in that direction.

Flex

Flex boxes themselves (Row and Column) behave differently based on whether they are in bounded constraints or unbounded constraints in their given direction.

In bounded constraints, they try to be as big as possible in that direction. In unbounded constraints, they try to fit their children in that direction. In this case, you cannot set flex on the children to anything other than 0 (the default). In the widget library, this means that you cannot use Expanded when the flex box is inside another flex box or inside a scrollable. If you do, you’ll get an exception message pointing you at this document. In the cross direction, for example, in the width for Column (vertical flex) or in the height for Row (horizontal flex), they must never be unbounded, otherwise they would not be able to reasonably align their children.

Dealing with box constraints — Structure map

Clickable & Draggable!

Dealing with box constraints — Related pages: