0
0
FlutterConceptBeginner · 3 min read

What is MediaQuery in Flutter: Explanation and Example

MediaQuery in Flutter is a widget that provides information about the size and orientation of the device screen or parent widget. It helps you build responsive layouts by letting your app adapt to different screen sizes and orientations dynamically.
⚙️

How It Works

Think of MediaQuery as a window that tells your app about the current screen’s size, orientation, and other display features. Just like when you adjust a picture frame to fit different wall sizes, MediaQuery helps your app adjust its layout to fit different devices.

When your app runs, MediaQuery collects information like screen width, height, pixel density, and orientation. You can then ask it for these details anywhere in your widget tree to make smart layout decisions, such as changing font sizes or rearranging buttons.

💻

Example

This example shows how to use MediaQuery to get the screen width and display it in the app.

dart
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('MediaQuery Example')),
        body: Builder(
          builder: (context) {
            final screenWidth = MediaQuery.of(context).size.width;
            return Center(
              child: Text('Screen width: $screenWidth pixels'),
            );
          },
        ),
      ),
    );
  }
}
Output
A screen showing an app bar with title 'MediaQuery Example' and centered text below: 'Screen width: 360.0 pixels' (value depends on device).
🎯

When to Use

Use MediaQuery whenever you want your app to look good on different screen sizes or orientations. For example:

  • Adjusting font sizes or padding for small vs large screens.
  • Changing layout from a column to a row when the device rotates.
  • Hiding or showing widgets based on available screen space.

This makes your app flexible and user-friendly on phones, tablets, or even web browsers.

Key Points

  • MediaQuery provides device and screen info to your app.
  • It helps build responsive and adaptive UI layouts.
  • You access it via MediaQuery.of(context).
  • Common properties include size, orientation, and padding.
  • Use it to improve user experience on different devices.

Key Takeaways

MediaQuery gives your app info about screen size and orientation.
Use MediaQuery to create layouts that adapt to different devices.
Access MediaQuery data with MediaQuery.of(context).
It helps make your app look good on phones, tablets, and more.
Responsive design improves usability and appearance.