What is the purpose of the Expanded widget in Flutter?
#flutter#widget#layout
Answer
Overview
The widget makes a child of a textExpanded
text
Rowtext
Columntext
FlexBasic Usage
dartRow( children: [ Text('Label: '), // Takes only the space it needs Expanded( child: TextField(), // Takes ALL remaining width ), ], )
How It Works
text|---Row--------------------------------------------| | [Text: 60px] | [Expanded fills remaining space→] | |--------------------------------------------------|
In Column
dartColumn( children: [ AppBar(), // Fixed height Expanded( child: ListView.builder(...), // Fills all remaining vertical space ), BottomNavigationBar(), // Fixed height ], )
Using flex for Proportional Sizing
dartRow( children: [ Expanded( flex: 2, // Takes 2/3 of space child: Container(color: Colors.blue), ), Expanded( flex: 1, // Takes 1/3 of space child: Container(color: Colors.red), ), ], )
Expanded vs Flexible
dart// Expanded: child MUST fill all allocated space Expanded(child: Container(color: Colors.blue)) // Flexible: child CAN be smaller than allocated space Flexible(child: Container(width: 50, color: Colors.red))
Common Use Cases
| Use Case | Example |
|---|---|
| TextField taking remaining row width | text |
| Body filling screen between AppBar & BottomBar | text |
| Equal-width columns | text |
| 2:1 ratio layout | text |
Note:
is just shorthand fortextExpanded. It always forces the child to fill its allocated space.textFlexible(fit: FlexFit.tight)