0
0
Fluttermobile~5 mins

Expanded and Flexible in Flutter

Choose your learning style9 modes available
Introduction

Expanded and Flexible help you control how widgets grow and share space inside a row or column. They make your app look neat on different screen sizes.

You want buttons or boxes to fill available space evenly in a row.
You want one widget to take more space than others inside a column.
You want to avoid overflow errors when screen size changes.
You want to create responsive layouts that adjust nicely on phones and tablets.
Syntax
Flutter
Expanded(
  flex: 1, // optional, default is 1
  child: Widget(),
)

Flexible(
  flex: 1, // optional, default is 1
  fit: FlexFit.loose, // or FlexFit.tight
  child: Widget(),
)
Expanded forces the child to fill the available space.
Flexible lets the child be smaller if it wants, depending on the fit.
Examples
Two containers share the row space equally.
Flutter
Row(
  children: [
    Expanded(
      child: Container(color: Colors.red),
    ),
    Expanded(
      child: Container(color: Colors.blue),
    ),
  ],
)
The green container takes twice the space of yellow. Yellow can be smaller if it wants.
Flutter
Row(
  children: [
    Flexible(
      flex: 2,
      fit: FlexFit.tight,
      child: Container(color: Colors.green),
    ),
    Flexible(
      flex: 1,
      fit: FlexFit.loose,
      child: Container(color: Colors.yellow, width: 50),
    ),
  ],
)
Sample App

This app shows a row with two colored boxes. The red box uses Expanded with flex 2, so it fills two parts of the space. The blue box uses Flexible with flex 1 and loose fit, so it only takes 50 pixels wide even if more space is available.

Flutter
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 and Flexible Example')),
        body: Row(
          children: [
            Expanded(
              flex: 2,
              child: Container(color: Colors.red, height: 100),
            ),
            Flexible(
              flex: 1,
              fit: FlexFit.loose,
              child: Container(color: Colors.blue, width: 50, height: 100),
            ),
          ],
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Use flex to control how much space each widget takes relative to others.

Expanded is like Flexible with fit: FlexFit.tight.

Flexible with FlexFit.loose lets the child be smaller than the available space.

Summary

Expanded makes a widget fill available space tightly.

Flexible lets a widget be flexible in size, either tight or loose.

Use these widgets inside Row or Column to create responsive layouts.