Answer
Overview
provides information about the current screen and device — size, orientation, text scale, pixel density, padding, and more. It's used to build responsive layouts based on the actual device screen.textMediaQuery
Basic Usage
dartWidget build(BuildContext context) { final mediaQuery = MediaQuery.of(context); final screenWidth = mediaQuery.size.width; final screenHeight = mediaQuery.size.height; return Container( width: screenWidth * 0.8, // 80% of screen width height: screenHeight * 0.3, color: Colors.blue, ); }
Commonly Used Properties
dartfinal mq = MediaQuery.of(context); mq.size.width // Screen width in logical pixels mq.size.height // Screen height in logical pixels mq.orientation // Orientation.portrait / landscape mq.devicePixelRatio // Physical pixels per logical pixel mq.textScaleFactor // User's text size preference mq.platformBrightness // Brightness.light / dark mq.viewInsets.bottom // Keyboard height when open mq.padding.top // Status bar / notch height mq.padding.bottom // Home indicator height
Responsive Layout with MediaQuery
dartWidget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return width > 600 ? Row(children: [Sidebar(), Content()]) // Tablet : Column(children: [Content()]); // Mobile }
Keyboard Detection
dart// Check if keyboard is open final bottomInset = MediaQuery.of(context).viewInsets.bottom; final isKeyboardOpen = bottomInset > 0; // Add padding above keyboard Padding( padding: EdgeInsets.only(bottom: bottomInset), child: TextFieldWidget(), )
Orientation Detection
dartWidget build(BuildContext context) { final isLandscape = MediaQuery.of(context).orientation == Orientation.landscape; return Flex( direction: isLandscape ? Axis.horizontal : Axis.vertical, children: [ImagePanel(), TextPanel()], ); }
Shorthand Accessors (Flutter 3.x+)
dart// Shorter syntax available in Flutter 3+ MediaQuery.sizeOf(context) // Size MediaQuery.orientationOf(context) // Orientation MediaQuery.paddingOf(context) // EdgeInsets MediaQuery.viewInsetsOf(context) // EdgeInsets (keyboard)
These only trigger rebuilds when the specific value changes — more efficient!
MediaQuery vs LayoutBuilder
| Feature | MediaQuery | LayoutBuilder |
|---|---|---|
| Measures | Full screen size | Parent widget constraints |
| Use case | App/screen level decisions | Widget/component level |
| Best for | Orientation, safe areas, keyboard | Reusable responsive components |
Best Practice: Use
for screen-level decisions (orientation, keyboard, dark mode). UsetextMediaQueryfor component-level responsiveness.textLayoutBuilder