In Flutter, Row and Column widgets are fundamental for laying out multiple child widgets either horizontally or vertically.
1. Basic Usage:
- Row: Arranges children horizontally.
- Column: Arranges children vertically.
Both accept a children property, which is a List<Widget>.
Code
// Example of a Row
Row(
children: <Widget>[
Container(width: 50, height: 50, color: Colors.red),
Container(width: 50, height: 50, color: Colors.green),
Container(width: 50, height: 50, color: Colors.blue),
],
)
// Example of a Column
Column(
children: <Widget>[
Container(width: 50, height: 50, color: Colors.red),
Container(width: 50, height: 50, color: Colors.green),
Container(width: 50, height: 50, color: Colors.blue),
],
)
2. Alignment:
You can control how children are positioned along the main axis (horizontal for Row, vertical for Column) and cross axis (vertical for Row, horizontal for Column).
mainAxisAlignment: Controls alignment along the main axis. Common values includeMainAxisAlignment.start,MainAxisAlignment.end,MainAxisAlignment.center,MainAxisAlignment.spaceBetween,MainAxisAlignment.spaceAround,MainAxisAlignment.spaceEvenly.crossAxisAlignment: Controls alignment along the cross axis. Common values includeCrossAxisAlignment.start,CrossAxisAlignment.end,CrossAxisAlignment.center,CrossAxisAlignment.stretch.
Code
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
// ... widgets
],
)
3. Expanding Children:
The Expanded widget is used to make a child of a Row or Column take up available space along the main axis. This is crucial for responsive layouts and preventing overflow errors.
- Wrap a child widget with
Expanded. - The
flexproperty (defaulting to 1) determines the proportion of available space the child should occupy relative to other expanded children.
Code
Row(
children: <Widget>[
Expanded(
flex: 2, // Takes twice as much space as the other Expanded child
child: Container(color: Colors.red),
),
Expanded(
flex: 1,
child: Container(color: Colors.green),
),
],
)
4. Nesting Rows and Columns:
Row and Column widgets can be nested within each other to create complex layouts.
Oops, something went wrong.
Also Read:-
Flutter key points mostly asked in flutter interviews
Dart basic programs mostly asked in interviews
