Flex Widgets (Row & Column)
Row and Column are flex widgets that arrange their children in a horizontal or vertical array. They are fundamental for creating layouts in Flitter.
Properties
Common properties for both Row and Column:
children
: Widget[] - List of child widgetsmainAxisAlignment
: MainAxisAlignment - How to place children along the main axis- “start” (default)
- “end”
- “center”
- “spaceBetween”
- “spaceAround”
- “spaceEvenly”
crossAxisAlignment
: CrossAxisAlignment - How to place children along the cross axis- “start”
- “end”
- “center”(default)
- “stretch”
mainAxisSize
: MainAxisSize - How much space to occupy in the main axis- “min”
- “max” (default)
verticalDirection
: VerticalDirection - The direction in which children are placed- “up”
- “down” (default)
clipped
: boolean - Whether to clip children to the container bounds (default: false)
Common Use Cases
-
Basic Row Layout:
Row({ children: [ Container({ width: 50, height: 50, color: "red", }), Container({ width: 50, height: 50, color: "blue", }), ], });
-
Centered Column:
Column({ mainAxisAlignment: "center", crossAxisAlignment: "center", children: [Text({ text: "Title" }), Text({ text: "Subtitle" })], });
-
Spaced Items:
Row({ mainAxisAlignment: "spaceBetween", crossAxisAlignment: "center", children: [Text({ text: "Left" }), Text({ text: "Right" })], });
Best Practices
-
Layout Guidelines:
- Choose appropriate axis alignment
- Consider cross-axis behavior
- Use consistent spacing
- Set clipped to true when overflow is possible
-
Performance:
- Avoid deeply nested flex widgets
- Consider using Expanded for flexible sizing
- Minimize rebuilds of flex layouts
-
Responsive Design:
- Handle overflow properly
- Consider screen size variations
- Use appropriate constraints
Common Patterns
-
Navigation Bar:
Row({ mainAxisAlignment: "spaceBetween", crossAxisAlignment: "center", children: [ IconButton({ icon: "menu" }), Text({ text: "Title" }), IconButton({ icon: "settings" }), ], });
-
Form Layout:
Column({ crossAxisAlignment: "stretch", mainAxisSize: "min", children: [ TextField({ label: "Username" }), TextField({ label: "Password" }), Button({ text: "Submit" }), ], });
-
Card Content:
Column({ crossAxisAlignment: "start", mainAxisSize: "min", children: [ Image({ src: "image.jpg" }), Text({ text: "Title" }), Text({ text: "Description" }), ], });
Tips and Tricks
-
Layout Debugging:
- Add background colors temporarily
- Check alignment boundaries
- Monitor flex behavior
- Use clipped property to identify overflow
-
Spacing Techniques:
- Use Container for gaps
- Consider mainAxisAlignment for spacing
- Maintain consistent spacing
-
Optimization:
- Cache flex widgets when possible
- Use const constructors
- Consider layout constraints
- Set appropriate mainAxisSize