flutter
/

Flutter MediaQuery Tutorial for Beginners

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Flutter MediaQuery Tutorial for Beginners

What is MediaQuery in Flutter?

MediaQuery is a powerful widget that provides information about the current device and app settings. It gives you access to the screen's dimensions, orientation, pixel density, text scaling factor, keyboard insets, and much more. MediaQuery is essential for creating responsive layouts that adapt to different screen sizes and device capabilities.

Accessing MediaQuery Data

To get the current MediaQuery data, use MediaQuery.of(context). This returns a MediaQueryData object containing all the information about the device. You can then read properties like size, orientation, devicePixelRatio, etc.

DARTRead-only
1
Widget build(BuildContext context) {
  final mediaQuery = MediaQuery.of(context);
  final screenWidth = mediaQuery.size.width;
  final screenHeight = mediaQuery.size.height;
  final orientation = mediaQuery.orientation;

  return Text('Width: $screenWidth, Height: $screenHeight, Orientation: $orientation');
}

Key Properties of MediaQueryData

  • size – The dimensions of the screen (in logical pixels).
  • width – Shortcut for size.width.
  • height – Shortcut for size.height.
  • orientation – Whether the device is in portrait or landscape (Orientation.portrait / Orientation.landscape).
  • devicePixelRatio – The number of device pixels for each logical pixel (used for scaling images).
  • textScaleFactor – The user's preferred font size scaling (e.g., for accessibility).
  • padding – The insets that parts of the display might be obscured by system UI (like the status bar or notches).
  • viewPadding – Similar to padding, but includes areas that are physically present (e.g., rounded corners).
  • viewInsets – The parts of the display that are completely obscured (like the keyboard).
  • alwaysUse24HourFormat – Whether the user prefers 24‑hour time format.
  • platformBrightness – The current brightness mode (light/dark theme).

Building Responsive Layouts

MediaQuery is the foundation of responsive design in Flutter. You can use its properties to change the layout based on screen size or orientation. For example, you might show a different number of columns in a grid depending on the screen width.

DARTRead-only
1
Widget build(BuildContext context) {
  final width = MediaQuery.of(context).size.width;
  int crossAxisCount = width > 600 ? 3 : 2;

  return GridView.count(
    crossAxisCount: crossAxisCount,
    children: List.generate(20, (index) => Card(child: Center(child: Text('Item $index')))),
  );
}

Performance Considerations: MediaQuery.of vs. Specific Getters

Calling MediaQuery.of(context) rebuilds the widget whenever any property of MediaQuery changes (e.g., orientation, text scale factor, or even the keyboard appearance). This can cause unnecessary rebuilds. To optimise performance, Flutter 3.10 introduced specific getters like MediaQuery.sizeOf(context) and MediaQuery.orientationOf(context). These only trigger rebuilds when the specific property changes.

DARTRead-only
1
// ❌ Rebuilds on any MediaQuery change
final width = MediaQuery.of(context).size.width;

// ✅ Rebuilds only when size changes
final width = MediaQuery.sizeOf(context).width;

// ✅ Rebuilds only when orientation changes
final orientation = MediaQuery.orientationOf(context);

Modifying MediaQuery

Sometimes you need to modify the MediaQuery for a subtree. For instance, you might want to remove system padding from a widget or force a different text scale factor. You can use MediaQuery.removePadding, MediaQuery.removeViewInsets, or wrap a widget with a new MediaQuery widget and provide your own MediaQueryData.

DARTRead-only
1
MediaQuery.removePadding(
  context: context,
  removeTop: true,
  child: ListView(/* ... */),
)

// Override text scale factor (e.g., disable user scaling)
MediaQuery(
  data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
  child: MyWidget(),
)

Handling Orientation Changes

You can listen to orientation changes using OrientationBuilder, which internally uses MediaQuery. It rebuilds only when the orientation changes, making it efficient.

DARTRead-only
1
OrientationBuilder(
  builder: (context, orientation) {
    return GridView.count(
      crossAxisCount: orientation == Orientation.portrait ? 2 : 4,
      children: /* ... */,
    );
  },
)

Common Mistakes Beginners Make

  • Calling MediaQuery.of(context) before the widget is inserted in the tree: This happens if you call it in a constructor or before build. Always call it inside build or in a place where context is valid.
  • Assuming MediaQuery is always available: If you haven't placed a MaterialApp or WidgetsApp above, there will be no MediaQuery. Make sure your app is wrapped accordingly.
  • Not handling null context: In some edge cases, MediaQuery.of(context) might throw if no ancestor provides it. Use maybeOf if you're unsure.
  • Overusing MediaQuery.of() and causing rebuilds: Use specific getters (sizeOf, orientationOf) where possible.
  • Forgetting that padding and viewInsets include system UI: When placing content at the bottom, remember to account for the keyboard using viewInsets.bottom.

Key Points to Remember

  • MediaQuery provides essential information about the device and app settings.
  • Use MediaQuery.of(context) to get the data; use specific getters (sizeOf, orientationOf) for better performance.
  • Responsive layouts often depend on size.width or orientation.
  • You can modify MediaQuery for a subtree using MediaQuery widget or helper methods like removePadding.
  • Always consider the impact of keyboard and system UI insets on your layout.

Common Interview Questions

  1. What is the difference between MediaQuery.of(context).size and MediaQuery.sizeOf(context)?
  2. How would you create a layout that changes from a list to a grid when the device is rotated?
  3. Explain the difference between padding, viewPadding, and viewInsets in MediaQueryData.
  4. How can you disable the user's system‑level text scaling inside a specific part of your app?
  5. What happens if you try to access MediaQuery before a MaterialApp? How would you handle that?
  6. Describe a scenario where you would use MediaQuery.removePadding.

Try it yourself

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('MediaQuery Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Screen width: ${MediaQuery.sizeOf(context).width.toStringAsFixed(1)}'),
              Text('Screen height: ${MediaQuery.sizeOf(context).height.toStringAsFixed(1)}'),
              Text('Orientation: ${MediaQuery.orientationOf(context)}'),
              Text('Text scale factor: ${MediaQuery.textScaleFactorOf(context)}'),
              const SizedBox(height: 20),
              const Text('Rotate your device to see changes!'),
            ],
          ),
        ),
      ),
    );
  }
}

Test Your Knowledge

Q1
of 3

How do you get the current screen width using MediaQuery?

A
MediaQuery.of(context).width
B
MediaQuery.sizeOf(context).width
C
Both A and B are valid, but B is more efficient
D
MediaQuery.getWidth(context)
Q2
of 3

Which MediaQuery property gives you the area obscured by the keyboard?

A
padding
B
viewPadding
C
viewInsets
D
keyboardInsets
Q3
of 3

What does `OrientationBuilder` use internally to detect orientation changes?

A
LayoutBuilder
B
MediaQuery
C
CustomPaint
D
WidgetsBindingObserver

Previous

flutter expanded

Next

flutter navigator

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.