Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Expanded vs Flexible

Scaffold(
  appBar: AppBar(),
  body: Column(
    children: <Widget>[
      Row(
        children: <Widget>[
          buildExpanded(),
          buildFlexible(),
        ],
      ),
      Row(
        children: <Widget>[
          buildExpanded(),
          buildExpanded(),
        ],
      ),
      Row(
        children: <Widget>[
          buildFlexible(),
          buildFlexible(),
        ],
      ),
    ],
  ),
);

enter image description here


Expanded is just a shorthand for Flexible

Using Expanded this way:

Expanded(
  child: Foo(),
);

is strictly equivalent to:

Flexible(
  fit: FlexFit.tight,
  child: Foo(),
);

You may want to use Flexible over Expanded when you want a different fit, useful in some responsive layouts.

The difference between FlexFit.tight and FlexFit.loose is that loose will allow its child to have a maximum size while tight forces that child to fill all the available space.


Widget under Flexible are by default WRAP_CONTENT although you can change it using parameter fit.

Widget under Expanded is MATCH_PARENT you can change it using flex.


Expanded - it is Flexible with set fit

class Expanded extends Flexible {
    const Expanded({
        Key key,
        int flex = 1,
        @required Widget child,
    }) : super(
        key: key, 
        flex: flex, 
        fit: FlexFit.tight, 
        child: child
    );
}

You may use Flexible to resize the widgets in rows and columns. It's mainly used to adjust the space of the different child widgets while keeping the relation with their parent widgets.

Meanwhile, Expanded changes the constraints sent to the children of rows and columns; it helps to fill the available spaces there. Therefore, when you wrap your child in an Expanded widget it fills up the empty spaces.

Providing these videos from the Flutter's Official YouTube channel just to help out people, who might look for this in the upcoming future...

  1. Expanded:

  2. Flexible:


Expanded() is nothing more than Flexible() with

Flexible (fit: FlexFit.tight) = Expanded()

but, Flexible uses fit :FlexFit.loose by default.

FlexFit.tight = Wants to fit tight into parent taking as much space as possible.

FlexFit.loose = Wants to fit loose into parent taking as little space as possible for itself.