D
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.

AspectLayoutBuilderMediaQuery
What it measuresParent's constraints for this widgetEntire device/window metrics
Reacts toLocal container size changesScreen rotation, font scale, notches
Rebuild costOnly this subtreeEvery consumer in the tree
Best forComponent-level responsivenessApp-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