LayoutBuilder: Build Widgets Based on Parent Size
LayoutBuilder lets your widget ask its parent "how much space do I have?" before deciding what to build. Use it for responsive layouts, like showing a Row on wide screens and a Column on narrow ones.
WHY IT EXISTS In Flutter's layout system, parents typically dictate size constraints to children without knowing what the child will be. LayoutBuilder was created to invert this, allowing a widget to know its parent's constraints before it decides what to build, enabling truly responsive components.
THE MENTAL MODEL Think of LayoutBuilder as a "just-in-time" widget builder. Instead of building a fixed widget tree, it waits until the layout phase, inspects the size constraints given by its parent, and then runs a builder function to construct a widget tree perfectly suited for that specific space.
HOW IT WORKS You provide LayoutBuilder a builder function that receives the BuildContext and, crucially, a BoxConstraints object. During layout, Flutter invokes this function, passing in the constraints from the parent. Your function can then use properties like constraints.maxWidth to conditionally return different widgets. The LayoutBuilder itself then sizes to match the child widget it creates.
WHEN TO USE IT Use LayoutBuilder to create adaptive components that change based on their allocated space, not the entire screen. A classic example is a component that renders as a wide Row in a large container but reflows into a stacked Column when placed in a narrow one. This makes your widgets reusable and context-aware.
WHEN NOT TO USE IT Do not use LayoutBuilder when you need the global screen size; MediaQuery.of(context).size is the correct tool for that. If your widget's appearance does not depend on its parent's size, LayoutBuilder adds unnecessary complexity and overhead compared to a standard widget or a simple Builder.
ONE CANONICAL EXAMPLE A common pattern is to build a different widget depending on the available width. Inside the builder function, you check if (constraints.maxWidth > 600). If true, return a Row for a wide layout. If false, return a Column for a narrow, stacked layout. This allows the same widget to adapt gracefully to different parts of an application's UI.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.