All 7 Responsive & Adaptive UI Design questions
More in Responsive & Adaptive UI Design
Advertisement
Back to results for “Media”
Flutter › Responsive & Adaptive UI Design

What is the difference between using MediaQuery and using LayoutBuilder for making a genuine responsive layout decision, and when would you genuinely prefer one particular approach over the other?

Intermediate

Answer

MediaQuery provides information about the entire overall device screen, regardless of exactly where within the widget tree you actually happen to be, while LayoutBuilder instead provides the genuine actual available constraints specifically passed down to that particular widget's own specific position within the tree, which can genuinely differ meaningfully from the full overall screen size if that particular widget happens to be nested within a considerably narrower parent, such as a side panel or a specific column within a larger grid, meaning LayoutBuilder generally provides genuinely more accurate, contextually specific information whenever a given widget's own actual available space might genuinely differ from the full overall device screen size.
LayoutBuilder(
  builder: (context, constraints) {
    return constraints.maxWidth > 300 ? WideCard() : NarrowCard();
  },
)
Real-world example A dashboard widget nested within a considerably narrow side panel properly uses LayoutBuilder rather than MediaQuery to correctly make its own layout decisions based on its own genuinely actual available narrower space, rather than incorrectly basing those decisions on the entire overall device screen's own considerably wider full size.

Common follow-ups: Can you actually properly combine both MediaQuery and LayoutBuilder together within exactly the same single given widget?;What genuinely happens if you use MediaQuery within a widget nested deep inside a genuinely narrow specific container?