पाठ 7 / 25
Row, Column and Constraints
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.
Sharing space in a Row
Expanded, Flexible and alignment.
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.
त्वरित जाँच: A Text inside a Row overflows. What is the usual fix?
- 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.