Sub topic 2
Controlling how much space a Row or Column takes
This chapter assumes you know Dart classes and named parameters, can write a StatelessWidget with a build method, and can run a Flutter app.
Row and Column size
A Row or Column lays out its children along a main axis (horizontal for Row, vertical for Column). By default, mainAxisSize is MainAxisSize.max, so the widget fills all the space its parent allows. Set MainAxisSize.min to shrink it to fit its children.
Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.star),
Text('4.8'),
],
)Adding space with SizedBox and Padding
A SizedBox with a width or height creates a fixed gap between siblings. Padding adds space around one child. Use SizedBox for gaps between items and Padding for insets around a single widget.
Sharing space with Expanded, Flexible, and Spacer
Expanded makes a child take the leftover main-axis space. Its flex value sets its share of that space. Flexible works the same way, but the child may be smaller than its share. Spacer() is an empty Expanded that pushes its siblings apart.
Row(
children: [
Expanded(flex: 2, child: Container(height: 50, color: Colors.blue)),
Expanded(child: Container(height: 50, color: Colors.red)),
],
)The blue box gets two thirds of the width, and the red box gets one third.
Fixing overflow and unbounded-constraint errors
A RenderFlex overflow occurs when children need more space than the Row or Column provides. Wrap the text in Expanded and add overflow: TextOverflow.ellipsis.
Layering widgets with Stack
A Stack paints its children on top of each other, with later children on top. Positioned pins a child to specific edges.
Stack(
children: [
Positioned.fill(child: ColoredBox(color: Colors.grey)),
Positioned(
right: 8,
bottom: 8,
child: Icon(Icons.favorite, color: Colors.red),
),
],
)Exercise
A Row holds a long Text next to an Icon, and the screen shows a yellow and black overflow stripe. How do you fix it?
Show answer
The Text requests more width than the Row has. Wrap the Text in Expanded so it receives bounded width, and set overflow: TextOverflow.ellipsis so it truncates instead of overflowing.