# Row, Column and Constraints — Flutter

Source: https://www.skillbyai.com/en/flutter/l-flex

> Flex layout and the layout rule.

## The one rule of Flutter layout

Flutter layout follows one rule: **constraints go down, sizes go up, the parent sets position**. A parent passes min and max width and height (`BoxConstraints`) to each child; the child chooses a size inside them; the parent then positions the child. **Row** and **Column** lay children out along a main axis; `mainAxisAlignment` and `crossAxisAlignment` control spacing and alignment. Children are first given unbounded space along the main axis, so a long `Text` or a nested list can overflow (the yellow-and-black stripes in debug mode). Wrap such children in **Expanded** (takes the remaining space, forced to fill it) or **Flexible** (may use up to its share), each with an optional `flex` factor.

## Constraints go down, sizes go up

Every widget gets constraints from its parent, picks a size within them, and the parent decides where to place it.

![Three ideas: flex layout and constraints, single-child layout widgets, responsive and scrolling layouts.](assets/figures/flutter/section-3-map.svg) — Figure 3.1 — Constraints flow down, sizes flow up, the parent sets position.

## Sharing space in a Row

Expanded, Flexible and alignment.

```dart
Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  crossAxisAlignment: CrossAxisAlignment.center,
  children: [
    const Icon(Icons.music_note),
    Expanded(
      flex: 2, // gets twice the space of the Flexible below
      child: Text(
        'A very long song title that would otherwise overflow',
        overflow: TextOverflow.ellipsis,
      ),
    ),
    Flexible(
      child: Text('3:45', textAlign: TextAlign.end),
    ),
  ],
)
```

## A manager handing out desks

The parent tells each child how much room it may use, the child says how big it will be, and the manager decides where its desk goes. Children never pick their own position.

**Quiz:** A Text inside a Row overflows. What is the usual fix?

- [x] Wrap it in Expanded or Flexible so it is given a bounded width
- [ ] Wrap the Row in a Center
- [ ] Add a ValueKey
- [ ] Call setState

*Answer:* Wrap it in Expanded or Flexible so it is given a bounded width. Row gives children unbounded main-axis space unless they are flexible.
