tezvyn:

LayoutBuilder versus MediaQuery for responsive widgets

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

knowing layout constraints versus screen metrics.

OUTLINE

MediaQuery reports the whole window; LayoutBuilder gives the parent's actual constraints.

RED FLAG

claiming they are interchangeable for sizing nested components.

WHAT THIS TESTS The interviewer wants to see that you understand the difference between Flutter's global window metrics and the local constraint system, and that you pick the right tool for where a widget actually lives in the tree.

A GOOD ANSWER COVERS MediaQuery.of(context) exposes properties of the whole application window: size, devicePixelRatio, padding, viewInsets and orientation. It is ideal for app-level breakpoint decisions like switching from a single column to a master-detail layout. LayoutBuilder, by contrast, provides a builder callback with the BoxConstraints handed down by the parent widget, so it tells you the space your widget genuinely has to fill. You choose LayoutBuilder when a component must adapt to its container rather than the device.

COMMON WRONG ANSWERS Treating the two as interchangeable, or always reaching for MediaQuery because it is easier. Another mistake is calling MediaQuery.of in many leaf widgets, which subscribes them all to window changes and triggers extra rebuilds on keyboard show or rotation.

LIKELY FOLLOW-UPS How does MediaQuery cause rebuilds via InheritedWidget. When does LayoutBuilder rebuild. How do viewInsets versus padding differ when the keyboard appears. Could you combine both.

ONE CONCRETE EXAMPLE Imagine a tablet app with a fixed 300-pixel sidebar and a content pane. A card widget in the content pane reads MediaQuery width of 1024 and decides to show three columns, but its real slot is only 724 pixels wide, so the columns overflow and clip. Wrapping that card in a LayoutBuilder lets it read constraints.maxWidth of 724 and choose two columns correctly. The same problem appears inside dialogs, bottom sheets and split-screen multitasking, where window size and available width diverge sharply.

Read the original → docs.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.