Flutter expanded widget explanation with example

Expanded widget of flutter:

Expanded widget can be used with a Row, Column or Flex widget. It is used to expand the childs to fill all available spaces. One thing you should note that this widget should be a descendent of Row, Column or Flex. We can also provide one flex property to these elements to change the expanded space.

Expanded with a Column:

Let’s try with Column first. For the below example widget,

class DemoPage extends StatelessWidget {
  
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          title: Text('Expanded Demo'),
        ),
        body: Center(
          child: Column(
            children: [
              Container(
                color: Colors.cyan,
                width: 200,
                height: 200,
              ),
              Container(
                color: Colors.red,
                width: 200,
                height: 200,
              ),
              Container(
                color: Colors.green,
                width: 200,
                height: 200,
              )
            ],
          ),
        ));
  }
}

It will give the below output:

flutter column example

Now, if I use Expanded for the first and the last Container,

child: Column(
children: [
    Expanded(
    child: Container(
    color: Colors.cyan,
    width: 200,
    )),
    Container(
    color: Colors.red,
    width: 200,
    height: 200,
    ),
    Expanded(
    child: Container(
    color: Colors.green,
    width: 200,
    ))
],
),

We can remove the height for Expanded and it will expand both to fill the remaining space:

flutter expanded column

Expanded with Row:

We can also use it with Row:

body: Center(
        child: Row(
        children: [
            Expanded(
            child: Container(
            color: Colors.cyan,
            height: 200,
            )),
            Container(
            color: Colors.red,
            width: 20,
            height: 200,
            ),
            Expanded(
            child: Container(
            color: Colors.green,
            height: 200,
            ))
        ],
        ),
    ));

flutter expanded row

Expanded with flex:

We can use flex with Expanded to change the size relatively:

body: Center(
        child: Row(
        children: [
            Expanded(
            flex: 1,
            child: Container(
            color: Colors.cyan,
            height: 200,
            )),
            Container(
            color: Colors.red,
            width: 20,
            height: 200,
            ),
            Expanded(
            flex: 3,
            child: Container(
            color: Colors.green,
            height: 200,
            ))
        ],
        ),
    ));

This will result the below output: flutter expanded flex

You might also like: