tezvyn:

Expanded & Flexible: Claiming Space in Flutter Layouts

AI-drafted, machine-checkedSource: docs.flutter.devbeginner

Expanded and Flexible widgets manage space in a Row or Column. Expanded is greedy, forcing its child to fill all available space. Flexible is polite, allowing its child to grow but not requiring it. Use them to prevent overflow errors.

WHY IT EXISTS: In a responsive UI, you can't hardcode every widget's size. Expanded and Flexible were created to solve the problem of distributing available space within a container (Row or Column) among its children, preventing pixel overflows and creating layouts that adapt gracefully to different screen dimensions.

THE MENTAL MODEL: Think of widgets in a Row or Column negotiating for leftover space. A regular widget states its size and is done. An Expanded widget is greedy: it demands to fill all remaining space. A Flexible widget is polite: it can grow to fill the space if needed, but is also happy with its natural size if it's smaller. The flex property is their negotiation power; a widget with flex: 2 gets twice the space of one with flex: 1.

HOW IT WORKS: Both widgets must be children of a Row, Column, or Flex. These parents first measure their non-flexible children. Then, they divide the remaining space among their Flexible and Expanded children based on the flex factor of each. Expanded is simply a shorthand for Flexible with its fit property set to FlexFit.tight, meaning it MUST fill the space it's given. Flexible defaults to FlexFit.loose, meaning it CAN fill the space, but can also be smaller.

WHEN TO USE IT: Use Expanded when you want a widget to definitively fill the rest of the main axis, like a title text between two icons in an app bar. Use Flexible when a widget should expand to avoid overflow but shouldn't be forced to stretch if it doesn't need to, like a block of text that might wrap.

WHEN NOT TO USE IT: Never use Expanded or Flexible outside of a Row, Column, or Flex widget. Doing so will cause a runtime error because they have no "flex" parent to get layout instructions from. Also, be cautious using Expanded inside a scrollable parent like ListView, as the available space can be infinite, leading to layout errors unless constrained.

ONE CANONICAL EXAMPLE: Consider a Row with an Icon, a Text widget, and another Icon. If you wrap the Text widget with Expanded, it will automatically consume all the space between the two icons, pushing the second icon to the far right. This ensures the layout looks correct on both a narrow phone and a wide tablet without any manual calculations.

Read the original → docs.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.