Question #309MediumWidgets & UI

What is the purpose of the Flex widget in Flutter?

#flutter#widget#layout

Answer

Overview

The

text
Flex
widget is the base class that both
text
Row
and
text
Column
are built on. It lays out children along a configurable axis — either horizontal or vertical.


Flex vs Row vs Column

WidgetWhat it is
text
Flex
Base widget — axis is configurable
text
Row
text
Flex
with
text
direction: Axis.horizontal
text
Column
text
Flex
with
text
direction: Axis.vertical

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
Flex
is when you need to switch axis dynamically based on screen size or orientation:

dart
class 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

dart
Flex(
  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
text
Flex
vs
text
Row
/
text
Column

SituationUse
Always horizontal layout
text
Row
(clearer intent)
Always vertical layout
text
Column
(clearer intent)
Axis changes at runtime (responsive)
text
Flex
Building a reusable layout widget
text
Flex

In practice: You will rarely use

text
Flex
directly. Use
text
Row
and
text
Column
for clarity. Use
text
Flex
when you need runtime axis switching.