What's the difference between LayoutBuilder and MediaQuery for responsive design?
Short Answer
MediaQuery gives you the entire screen/device's size and metrics; LayoutBuilder gives you the constraints of just the specific widget it wraps, which is what you actually want for responsive decisions inside nested widgets.
MediaQuery.of(context).size returns the full screen dimensions, useful for app-wide decisions (tablet vs phone layout) but misleading inside a widget that isn't full-screen — a widget inside a 300px-wide side panel has no way to know that from MediaQuery, since it doesn't know about local layout constraints.
LayoutBuilder instead gives you a BoxConstraints object representing exactly how much space the parent has given this specific widget, via its builder callback. This makes it the correct tool for building a widget that adapts to whatever space it's actually placed in, rather than assuming it occupies the full screen.
Code Example
LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < 600) {
return const MobileLayout();
}
return const TabletLayout();
},
)Common Mistakes
- ×Using MediaQuery.of(context).size.width to decide a widget's internal layout when the widget isn't actually full-width.
- ×Rebuilding on every MediaQuery change when only a specific dimension is needed — MediaQuery.of triggers a rebuild on any metric change (including keyboard insets) unless you select just the piece you need.