Flutter- Flexible vs Expanded

Flutter- Flexible vs Expanded

Introduction

I have decided to start a series called this vs that in Flutter. In this series, I will explain the difference between two widgets, methods, and packages which have some similarities and some differences.

In the first article, we will have a look at the Expanded and Flexible widget. We will see how they are different from each other and what similarities do they have. So, let's get started

Expanded

If a widget is wrapped with Expanded, then it will take the whole available space on the screen. For example, have a look at the below image. Screenshot (136).png

The green color container takes a height of 200. The red color container takes up the whole remaining space because it is wrapped with an Expanded. The Expanded widget tells its child widget to take up the remaining free space.

Flexible

If a widget is wrapped with Flexible, then it will change its size depending upon the space taken by other widgets. That is why it is called "Flexible". For example, in the above example, if we change the Expanded widget to Flexible, we will get the same output.

This happens because the second container is taking 200 px of height and then our Container is Flexible takes the rest of the space. If we wrap the second Container in Expanded then you will see both the containers will take half of the screen. Screenshot (137).png

One attribute that Flexible has and Expanded doesn't is that Flexible has something called flex. Flex allows you to define how much proportion of the screen its child widget must take. Have a look at this image, I have given a flex of 2 to the first container. This means that it will take 2/3rd of the screen. Screenshot (138).png

Differences

Now that we know what both the widget does, here are a few key things that we noticed

  1. Expanded is just like Flexible but with strict bounds. Flexible is not strict like Expanded
  2. 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 relationship with their parent widgets.
  3. 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.

Conclusion

So with this, we conclude this article on this vs that. We have seen what an expanded widget is, what a flexible widget is, and where can we use them. I hope you understood the concept of Flexible and Expanded.

You can appreciate and support my blogs via. bmcoffee.png

Also, let's connect on Twitter. Follow CSwithIyush for more amazing tutorials, tips/tricks on Flutter & DSA.

Did you find this article valuable?

Support Ayush Pawar by becoming a sponsor. Any amount is appreciated!