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.
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'), ); }, ), ), ); } }
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, andpadding. - Use it to improve user experience on different devices.