Question #341MediumWidgets & UI

What is a MediaQuery in Flutter?

#mediaquery#responsive#device

Answer

Overview

text
MediaQuery
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.


Basic Usage

dart
Widget 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

dart
final 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

dart
Widget 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

dart
Widget 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

FeatureMediaQueryLayoutBuilder
MeasuresFull screen sizeParent widget constraints
Use caseApp/screen level decisionsWidget/component level
Best forOrientation, safe areas, keyboardReusable responsive components

Best Practice: Use

text
MediaQuery
for screen-level decisions (orientation, keyboard, dark mode). Use
text
LayoutBuilder
for component-level responsiveness.