Flexible Widget Flutter: What It Is and How It Works
Flexible widget in Flutter lets a child widget expand or shrink to fill available space within a Row, Column, or Flex container. It controls how much space the child takes relative to its siblings using a flex factor, helping create flexible and responsive layouts.How It Works
The Flexible widget acts like a flexible container inside a Row, Column, or Flex layout. Imagine you have a box divided into parts, and you want some parts to grow or shrink depending on the space available. Flexible lets its child widget take up space based on a ratio called the flex factor.
For example, if you have two Flexible widgets with flex values 1 and 2, the second one will take twice as much space as the first. This helps your app adjust nicely on different screen sizes without fixed widths or heights.
It’s like having stretchy rubber bands that expand or contract to fill the space evenly or unevenly, depending on your design.
Example
This example shows a Row with three colored boxes. The middle box uses Flexible with a flex of 2, so it takes twice the space of the others.
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Flexible Widget Example')), body: Row( children: [ Container(color: Colors.red, width: 50, height: 100), Flexible( flex: 2, child: Container(color: Colors.green, height: 100), ), Container(color: Colors.blue, width: 50, height: 100), ], ), ), ); } }
When to Use
Use Flexible when you want child widgets inside a Row, Column, or Flex to share available space in a flexible way. It is helpful for responsive designs where fixed sizes don’t work well on different screen sizes.
For example, use Flexible to:
- Make buttons or text fields grow to fill space evenly.
- Adjust layout proportions dynamically when screen size changes.
- Prevent overflow errors by allowing widgets to shrink if needed.
It works well when you want some parts of your UI to stretch while others keep fixed sizes.
Key Points
- Flexible controls how a child widget expands or shrinks inside
Row,Column, orFlex. - The
flexproperty sets the relative space the child takes compared to siblings. - It helps create responsive layouts that adapt to screen size changes.
- Use it to avoid fixed sizes and allow widgets to share space dynamically.
- It differs from
Expandedby allowing the child to be smaller than the allocated space if needed.