Expanded vs Flexible: Understanding the Differences in Flutter

In this article, we explore the similarities and differences between the Expanded and Flexible classes in Flutter, and how they behave when used to layout widgets.

Learn the differences between the Expanded and Flexible classes in Flutter and how they affect the layout of widgets.


Do you know that Expanded is also Flexible?

Yes, you heard it right. Expanded is nothing but an extended class of Flexible.

Look at both codes. 



If we look closely at the above codes, we can see only one change and that is we added ` height:100` in the container (inside of expanded & flexible). But this small change gave us different results.

So, if the child in flexible knows its height (in Column and width in Row) then it will take the mentioned height. But if the height is not mentioned then it will take the remaining height and it will act like an expanded widget.


And expanded widget will always take remaining height (or width).

Expanded Widget:

The Expanded Widget is a single child widget. This means that it can have only one child assigned to it. To make this widget work properly, it must be used inside a row or column. And if we equate our child to the widget if we do not want to give the space. We can distribute to that location. We will use flex to distribute this space.

Properties of Expanded Widget:

child: Child widget is used to place inside the expanded widget. Which we can take in rows and columns.

Flex: The flex property, which uses flex to distributes the available space unevenly between child widgets.


To understand it better, see the code below.


Expanded(
         flex: 1,// default
         child: Container(),// required field
       ),



Flexible Widget:

Flexible widgets are basically similar to extends widgets. But there is a slight difference in properties. It is mainly used to adjust different child widgets' location while having a relationship with their parent widgets.


Properties of Flexible Widget:

fit: The fit property controls that. How does the child widget fill the available space?


It has Three options.

1.FlexFit. Tight: Sets it to fill the remaining available space.

2.FlexFit.loose: Sets it to fill the remaining available space. This is as much as the space available to the child widget; let’s grow up.

3.Flex: The flex property, which uses flex to distributes the available space unevenly between child widgets.


To understand it better, see the code below.



Flexible(
           flex: 1, // default value
           fit:  FlexFit.loose, //default value
           child: Container(), // required field
        ),

..

Comments