Builds Flutter layouts using the constraint system and layout widgets. Use when creating or refining the UI structure of a Flutter application.
Master the fundamental Flutter layout rule: Constraints go down. Sizes go up. Parent sets position.
x and y coordinates of a child Widget exclusively within the parent Widget. Children do not know their own position on the screen.double.infinity) in the cross-axis of a flex box (Row or Column) or within scrollable regions (ListView). This causes render exceptions.Select the appropriate structural Widget based on the required spatial arrangement.
Row and Column: Implement Row for horizontal linear layouts and Column for vertical linear layouts. Control child alignment using mainAxisAlignment and crossAxisAlignment.Expanded and Flexible: Wrap children of Row or Column in Expanded to force them to fill available space, or Flexible to allow them to size themselves up to the available space.Container: Wrap Widgets in a Container when you need to apply padding, margins, borders, or background colors.Stack: Implement Stack when Widgets must overlap on the Z-axis. Use Positioned to anchor children to specific edges of the Stack.SizedBox: Enforce strict, tight constraints on a child Widget by wrapping it in a SizedBox with explicit width and height values.Apply conditional logic to handle varying screen sizes and form factors.
LayoutBuilder, Expanded, and Flexible to dynamically adjust the size and placement of elements based on the parent's constraints.Follow this sequential workflow to architect and implement robust Flutter layouts.
Stack).ListView or SingleChildScrollView).ListView inside a Column).Scaffold and primary structural Widgets.Expanded (if inside a flex box) or wrap the parent in a scrollable Widget.Anti-pattern: Placing a ListView directly inside a Column causes an unbounded height exception because the Column provides infinite vertical space to the ListView.
// BAD: Throws unbounded height exception
Column(
children: [
Text('Header'),
ListView(
children: [/* items */],
),
],
)
Implementation: Wrap the ListView in an Expanded Widget to bound its height to the remaining space in the Column.
// GOOD: ListView is constrained to remaining space
Column(
children: [
Text('Header'),
Expanded(
child: ListView(
children: [/* items */],
),
),
],
)
Implement LayoutBuilder to conditionally render different structural Widgets based on available width.
Widget buildAdaptiveLayout(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
// Conditional logic based on screen width
if (constraints.maxWidth > 600) {
// Tablet/Desktop: Side-by-side layout
return Row(
children: [
SizedBox(width: 250, child: SidebarWidget()),
Expanded(child: MainContentWidget()),
],
);
} else {
// Mobile: Stacked layout with navigation
return Column(
children: [
Expanded(child: MainContentWidget()),
BottomNavigationBarWidget(),
],
);
}
},
);
}