Sub topic 4
Reading window information with MediaQuery
This chapter assumes you can write StatelessWidget and StatefulWidget classes, use Dart 3 syntax, and know how Scaffold, Row and Column work. It also assumes you have read the earlier chapter on constraints, where parents pass constraints down and children report sizes up. Here you learn what MediaQuery tells you, which accessor to call, and where its answers stop being correct.
What MediaQuery is
MediaQuery is an InheritedWidget. It holds a MediaQueryData object that describes the view your app is drawn into. MaterialApp and WidgetsApp create it for you from the platform window, so any widget below them can read it.
The data includes the following:
size: the width and height of the view in logical pixels.devicePixelRatio: how many physical pixels make up one logical pixel.orientation: portrait or landscape, derived from the size.padding,viewPaddingandviewInsets: areas covered by the system, such as notches, status bars, home indicators and the on-screen keyboard.textScaler: the user's font scaling preference.platformBrightness: whether the system is in light or dark mode.accessibleNavigation,disableAnimationsandboldText: accessibility settings.
A logical pixel is the unit Flutter layout uses. It is independent of screen density, so a 600-wide layout is the same on a dense phone screen and a plain monitor.
Choosing an accessor
The old way to read the data is MediaQuery.of(context). It returns the whole MediaQueryData and makes your widget depend on all of it. Any change to any field, such as the keyboard animating open, rebuilds the widget.
Current Flutter versions provide one accessor per field. Each one makes your widget depend only on that field.
| Accessor | Returns | Rebuilds when |
|---|---|---|
| `MediaQuery.sizeOf(context)` | `Size` | The view size changes |
| `MediaQuery.orientationOf(context)` | `Orientation` | The orientation changes |
| `MediaQuery.devicePixelRatioOf(context)` | `double` | The pixel ratio changes |
| `MediaQuery.paddingOf(context)` | `EdgeInsets` | Safe-area padding changes |
| `MediaQuery.viewInsetsOf(context)` | `EdgeInsets` | The keyboard or similar overlays change |
| `MediaQuery.textScalerOf(context)` | `TextScaler` | The text scale setting changes |
| `MediaQuery.platformBrightnessOf(context)` | `Brightness` | The system theme changes |
Prefer these accessors in all new code. The reason is performance, not correctness. A widget that only needs the width should not rebuild every frame while the keyboard slides up.
import 'package:flutter/material.dart';
class WindowInfo extends StatelessWidget {
const WindowInfo({super.key});
@override
Widget build(BuildContext context) {
final size = MediaQuery.sizeOf(context);
final orientation = MediaQuery.orientationOf(context);
final ratio = MediaQuery.devicePixelRatioOf(context);
return Text(
'${size.width.round()} x ${size.height.round()} dp, '
'${orientation.name}, pixel ratio $ratio',
);
}
}Each *Of method has a maybe*Of version, such as MediaQuery.maybeSizeOf. It returns null when no MediaQuery is above the widget. The plain version throws instead. Use the maybe form only in code that may run outside an app, such as a reusable package widget or a test that does not wrap the widget in MaterialApp.
Where you can call it
MediaQuery lookups register a dependency, so they follow the same rules as any inherited widget.
- Call them in
build, or indidChangeDependencies. Both run again when the data changes. - Do not call them in
initState. Flutter throws there, because the dependency cannot be registered yet. - Do not call them in callbacks, such as
onPressed, and store the result. The stored value goes stale. If a callback needs a value, read it inbuildand capture it, or read it fresh inside the callback for a one-off check.
Caching the size in a State field is a common bug. After a window resize or a rotation, the field still holds the old value.
Window size is not your widget's size
MediaQuery.sizeOf returns the size of the whole view. That is the right answer when you are deciding something about the whole screen, such as whether the app shell uses a bottom bar or a rail. The shell from the navigation chapter does exactly this:
final useRail = MediaQuery.sizeOf(context).width >= 600;It is the wrong answer when a widget lives in a part of the screen. Suppose a product card sits in a 300-wide side panel on a 1200-wide window. MediaQuery reports 1200, so the card believes it has lots of room and overflows. The next chapter covers LayoutBuilder, which reports the constraints the parent actually gives. The working rule is this:
- Use
MediaQueryfor facts about the window or device: window class, orientation, insets, text scale, theme. - Use
LayoutBuilderfor facts about the space a widget was given.
Dialogs, bottom sheets, split panes and multi-window desktop apps are the usual places where the two answers differ.
Safe areas and the keyboard
Three fields describe areas the app cannot fully use, and they are easy to confuse.
viewPaddingis the physical overlap with system UI such as notches and status bars. It does not change when the keyboard opens.paddingisviewPaddingminus the parts already consumed by something above in the tree, and minus the keyboard.viewInsetsis the part of the view completely covered, mainly by the keyboard.
The keyboard is the clearest case. When it opens, viewInsets.bottom becomes the keyboard height. Scaffold already reads this and shrinks its body when resizeToAvoidBottomInset is true, which is the default. You need to read viewInsets yourself when you build something outside a Scaffold, such as a custom bottom sheet.
import 'package:flutter/material.dart';
class KeyboardAwareSheet extends StatelessWidget {
const KeyboardAwareSheet({super.key});
@override
Widget build(BuildContext context) {
final keyboardHeight = MediaQuery.viewInsetsOf(context).bottom;
return Padding(
padding: EdgeInsets.only(bottom: keyboardHeight),
child: const Padding(
padding: EdgeInsets.all(16),
child: TextField(decoration: InputDecoration(labelText: 'Comment')),
),
);
}
}SafeArea is a convenience widget built on padding. The chapter on safe areas and text scaling covers it, so this chapter only reads the values.
Text scale
Users can raise the system font size. MediaQuery.textScalerOf(context) returns a TextScaler, which converts a font size to the size actually drawn. The older textScaleFactor is deprecated, because a single number cannot describe the non-linear scaling that Android 14 and later perform.
Use the scaler when a layout depends on the real text size:
final scaler = MediaQuery.textScalerOf(context);
final scaledBody = scaler.scale(16); // size in logical pixels after scalingDo not disable scaling to make a layout fit. That hurts users who need large text. If a very large setting breaks a screen, you can limit the range for one subtree:
MediaQuery.withClampedTextScaling(
minScaleFactor: 1.0,
maxScaleFactor: 1.6,
child: const Text('Order summary'),
)Overriding MediaQuery for a subtree
Because MediaQuery is an inherited widget, you can place a new one above a subtree. copyWith keeps every field and changes only the ones you name.
MediaQuery(
data: MediaQuery.of(context).copyWith(
padding: EdgeInsets.zero,
),
child: child,
)Scaffold does this itself. After it places an AppBar, it removes the top padding for the body, so a SafeArea inside the body does not add the status bar height twice. If your padding value looks smaller than the device's notch, a widget above you has probably consumed it. Print MediaQuery.paddingOf(context) at several depths to find which one.
Testing with MediaQuery values
Tests start with an 800 by 600 logical window unless you change it. To test a different size, set the test view's physical size and pixel ratio, as the testing chapter does. MediaQuery then reports the matching logical size.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('MediaQuery reports the simulated window', (tester) async {
tester.view.physicalSize = const Size(1000, 500);
tester.view.devicePixelRatio = 2.0;
addTearDown(tester.view.reset);
late Size seen;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) {
seen = MediaQuery.sizeOf(context);
return const SizedBox();
},
),
),
);
expect(seen, const Size(500, 250));
});
}Logical size is physical size divided by the pixel ratio, so 1000 by 500 at ratio 2.0 gives 500 by 250. Forgetting this division is a frequent reason a test lands on the wrong breakpoint.
Common errors
- Calling
MediaQuery.ofeverywhere. It works but rebuilds more than needed. Switch to the specific accessor. - Reading it in
initState. Move the code tobuildordidChangeDependencies. - Using window width for a nested widget. Use
LayoutBuilderwhen the parent limits the space. - Using
orientationas a proxy for device type. A resizable desktop window or a split-screen phone can be landscape and narrow. Decide by width. - Using
MediaQueryaboveMaterialApp. The widget that buildsMaterialApphas noMediaQueryabove it, so the lookup fails. Move the code into a child widget.
Exercise
A product card shows a three-column layout when MediaQuery.sizeOf(context).width is at least 600. In a 1200-wide window you place it inside a 300-wide side panel, and it overflows. Why does this happen, and what should the card use instead?
Show answer
MediaQuery reports the size of the whole view (1200), not the 300 pixels the panel gives the card, so the card picks the wide layout without enough room. The card should read its parent's constraints with LayoutBuilder and decide from constraints.maxWidth.
Exercise
A widget needs the keyboard height, and a teammate calls MediaQuery.of(context).viewInsets.bottom in initState. What goes wrong, and what is the better call?
Show answer
Looking up an inherited widget in initState throws, because the dependency cannot be registered at that point. Read the value in build with MediaQuery.viewInsetsOf(context).bottom. That also limits rebuilds to changes in the insets.
Exercise
In a test, you set tester.view.physicalSize to Size(1200, 800) and leave devicePixelRatio at its default of 3.0. Which logical width does MediaQuery.sizeOf report, and which window-size class does that fall into with the 600 and 840 boundaries?
Show answer
1200 / 3.0 = 400 logical pixels, which is in the compact class (below 600). To simulate a 1200-wide window, also set tester.view.devicePixelRatio = 1.0.