Expanded Widget Flutter: What It Is and How to Use It
Expanded widget in Flutter is used inside a Row, Column, or Flex to make a child widget fill the available space. It tells Flutter to expand the child to use the remaining free space along the main axis, helping create flexible and responsive layouts.How It Works
The Expanded widget works like a stretchy rubber band inside a Row or Column. Imagine you have a box with some space, and you want one item inside to grow and fill all the leftover space. Wrapping that item with Expanded tells Flutter to stretch it as much as possible.
Without Expanded, widgets take only the space they need. But with Expanded, the child widget grows to fill the free space left after other widgets are laid out. This helps create flexible designs that adjust to different screen sizes.
Example
This example shows a Row with three colored boxes. The middle box is wrapped in Expanded, so it fills all the space between the other two boxes.
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('Expanded Widget Example')), body: Row( children: [ Container(width: 50, height: 50, color: Colors.red), Expanded( child: Container(height: 50, color: Colors.green), ), Container(width: 50, height: 50, color: Colors.blue), ], ), ), ); } }
When to Use
Use Expanded when you want a widget inside a Row, Column, or Flex to take up all the remaining space. This is helpful for creating flexible layouts that adapt to different screen sizes.
For example, in a chat app, you might want the message input box to stretch across the screen while buttons stay fixed size. Or in a navigation bar, you want some items to fill space evenly.
Key Points
- Expanded must be a child of
Row,Column, orFlex. - It tells the child to fill the remaining space along the main axis.
- Multiple
Expandedwidgets share space proportionally. - Use it to create responsive and flexible UI layouts.