Widget TreeIntermediate30 XP3 min read
When should you use LayoutBuilder vs MediaQuery for responsive layouts?
TL;DR: Use LayoutBuilder when you need the constraints available to your widget. Use MediaQuery when you need screen-level info like device pixel ratio, text scale factor, or system padding.
Full Answer
Both tools enable responsive design but operate at different levels.
| Aspect | LayoutBuilder | MediaQuery |
|---|---|---|
| What it measures | Parent's constraints for this widget | Entire device/window metrics |
| Reacts to | Local container size changes | Screen rotation, font scale, notches |
| Rebuild cost | Only this subtree | Every consumer in the tree |
| Best for | Component-level responsiveness | App-level screen info |
๐ฏ
Prefer LayoutBuilder for components so they work correctly even when embedded in non-full-screen contexts like dialogs or side panels. MediaQuery.sizeOf(context) (Flutter 3.10+) rebuilds less than MediaQuery.of(context).
Code Examples
dartResponsive layout with LayoutBuilder
Output
Renders DesktopLayout on wide screens, TabletLayout on medium, MobileLayout on narrow โ all within whatever container the widget lives in
Common Mistakes
- โUsing MediaQuery.of(context).size to determine component layout โ breaks inside dialogs or split screens
- โCalling MediaQuery.of(context) deep in a widget tree, causing unnecessary rebuilds on text scale changes
Interview Tip
๐ก
Mentioning MediaQuery.sizeOf() (available since Flutter 3.10) shows you keep up with Flutter updates โ it's more efficient than the full MediaQuery.of() call.
#LayoutBuilder#MediaQuery#responsive#adaptive#constraints