Menu
CoddyTech

Sharing Space With flex

Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 2 of 30.

When two children of a Row are both Expanded, they share the space equally: on a 390 pixel phone, 195 pixels each.

To share it unequally, give Expanded a flex:. It is a share, not a size. Flutter adds up the shares and splits the space by them:

Row(
  children: [
    Expanded(flex: 3, child: Container(color: Colors.red)),
    Expanded(flex: 1, child: Container(color: Colors.blue)),
  ],
)

The shares add up to 4, so red gets 3 quarters of the row and blue gets 1 quarter. A child with no flex: has a share of 1.

Because the shares are parts of the whole, the layout keeps its proportions on any screen width.

challenge icon

Challenge

Easy

Make the Chart box twice as wide as the Notes box. On the phone that is 260 and 130 pixels.

Try it yourself

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(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Dashboard')),
        body: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: Container(
                    height: 120,
                    color: Colors.teal,
                    child: const Center(
                      child: Text('Chart', style: TextStyle(color: Colors.white)),
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    height: 120,
                    color: Colors.amber,
                    child: const Center(child: Text('Notes')),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Layout That Fits

Practice on your own: Online Flutter compiler