What is the purpose of the Flex widget in Flutter?
#flutter#widget#layout
Answer
Overview
The widget is the base class that both textFlex
text
Rowtext
ColumnFlex vs Row vs Column
| Widget | What it is |
|---|---|
text | Base widget — axis is configurable |
text | text text |
text | text text |
Basic Usage
dart// This is equivalent to Row Flex( direction: Axis.horizontal, children: [ Text('Item 1'), Text('Item 2'), Text('Item 3'), ], ) // This is equivalent to Column Flex( direction: Axis.vertical, children: [ Text('Item 1'), Text('Item 2'), ], )
Dynamic Axis — The Main Use Case
The real power of
text
Flexdartclass ResponsiveLayout extends StatelessWidget { Widget build(BuildContext context) { final isLandscape = MediaQuery.of(context).orientation == Orientation.landscape; return Flex( direction: isLandscape ? Axis.horizontal : Axis.vertical, children: [ Expanded(child: ImagePanel()), Expanded(child: DetailsPanel()), ], ); } }
All Available Properties
dartFlex( direction: Axis.horizontal, // Required: horizontal or vertical mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, textDirection: TextDirection.ltr, verticalDirection: VerticalDirection.down, children: [...], )
When to Use textFlex
vs textRow
/textColumn
text
Flextext
Rowtext
Column| Situation | Use |
|---|---|
| Always horizontal layout | text |
| Always vertical layout | text |
| Axis changes at runtime (responsive) | text |
| Building a reusable layout widget | text |
In practice: You will rarely use
directly. UsetextFlexandtextRowfor clarity. UsetextColumnwhen you need runtime axis switching.textFlex