Menu
CoddyTech

LayoutBuilder Breakpoints

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

On a tablet, a mail app shows the menu beside the messages. On a phone there is no room, so the menu goes on top. The width where the layout changes is called a breakpoint.

LayoutBuilder tells you how much space a widget has, and lets you build something different for each size:

LayoutBuilder(
  builder: (context, constraints) {
    if (constraints.maxWidth < 600) {
      return Column(children: [menu, content]); // phone
    }
    return Row(children: [menu, content]); // tablet
  },
)

builder is a function Flutter calls with the space it has, in constraints. constraints.maxWidth is the widest the result may be. Under 600 pixels you return a Column; otherwise a Row. On a 390 pixel phone you see the column; on a 1000 pixel tablet, the row.

MediaQuery reads the whole screen. LayoutBuilder reads the space of one widget, so it still works when that widget is a panel inside a bigger page.

challenge icon

Challenge

Medium

The menu and the content always sit side by side, which is cramped on a phone. Use a LayoutBuilder with a breakpoint at 600 pixels:

  • narrower than 600: the menu above the content, in a Column
  • 600 or wider: side by side, in a Row, as now

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('Mail')),
        body: Row(
          children: [
            Expanded(
              child: Container(
                color: Colors.teal.shade100,
                child: const Center(child: Text('Menu')),
              ),
            ),
            Expanded(
              flex: 2,
              child: Container(
                color: Colors.white,
                child: const Center(child: Text('Content')),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
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