What is Flexible in Flutter?
Flexible is a widget that controls how a child of a Row, Column, or Flex flexes. It allows the child to share the available space along the main axis, but unlike Expanded, it does not force the child to fill the space. Instead, the child can be smaller than the available space (if fit is FlexFit.loose). Flexible is the base class for Expanded.
Basic Usage
Wrap any child with Flexible inside a Row or Column. Provide a flex factor to control the proportion of space, and optionally set fit to FlexFit.tight (forces fill) or FlexFit.loose (allows the child to be smaller).
DARTRead-only
1
Flexible vs Expanded
Expanded is simply Flexible(fit: FlexFit.tight). The key difference:
- Expanded forces its child to fill the remaining space.
- Flexible (with
FlexFit.loose) allows the child to be its natural size, but still gives it a share of the space.
DARTRead-only
1
Key Properties
- flex (default 1): The flex factor to use when distributing space.
- fit: Either
FlexFit.tight(force fill) orFlexFit.loose(allow smaller). - child: The widget being flexed.
Common Use Cases
- Allowing a widget to take available space but not stretch if its content is small.
- Creating responsive layouts where some items have natural widths.
- Combining with Expanded to mix fixed and flexible sizing.
Key Points to Remember
- Flexible must be a direct child of a flex widget (Row, Column, Flex).
- Use
FlexFit.loosewhen you want the child to have a say in its size. - Use
FlexFit.tight(or Expanded) when you want the child to fill the space. - The
flexproperty distributes space proportionally among all flex children.
Common Interview Questions
- What is the difference between Flexible and Expanded?
- How does
FlexFit.loosebehave? Give an example. - Can you use Flexible with a
flexof 0? What happens? - What happens if you put two Flexible widgets with different
fitvalues in the same Row?