MediaQuery helps your app adjust its layout based on the screen size and orientation. This makes your app look good on all devices.
0
0
MediaQuery for responsiveness in Flutter
Introduction
You want your app to look good on phones and tablets.
You need to change font size or button size depending on screen width.
You want to switch layout when the device is in landscape or portrait mode.
You want to get the device's screen height or width to position widgets.
You want to make sure your app works well on small or large screens.
Syntax
Flutter
MediaQuery.of(context).size.width MediaQuery.of(context).size.height MediaQuery.of(context).orientation
Use MediaQuery.of(context) inside a widget's build method.
size gives screen width and height in logical pixels.
Examples
Get the screen width to adjust widget size.
Flutter
double screenWidth = MediaQuery.of(context).size.width;Get the screen height to position widgets vertically.
Flutter
double screenHeight = MediaQuery.of(context).size.height;Check if device is in portrait or landscape mode.
Flutter
Orientation orientation = MediaQuery.of(context).orientation;
Sample App
This app shows a blue box that changes height based on device orientation. It also displays the screen width, height, and orientation inside the box.
Flutter
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: const ResponsiveBox(), ), ); } } class ResponsiveBox extends StatelessWidget { const ResponsiveBox({super.key}); @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; Orientation orientation = MediaQuery.of(context).orientation; return Center( child: Container( width: width * 0.8, height: orientation == Orientation.portrait ? height * 0.3 : height * 0.6, color: Colors.blue, child: Center( child: Text( 'Width: ${width.toStringAsFixed(0)}\nHeight: ${height.toStringAsFixed(0)}\nOrientation: ${orientation.name}', style: const TextStyle(color: Colors.white, fontSize: 18), textAlign: TextAlign.center, ), ), ), ); } }
OutputSuccess
Important Notes
Always call MediaQuery.of(context) inside the build method or where context is valid.
Use orientation.name to get 'portrait' or 'landscape' as a string.
Logical pixels are device-independent pixels, so your UI scales well on different screens.
Summary
MediaQuery helps your app adapt to different screen sizes and orientations.
Use MediaQuery.of(context).size to get screen width and height.
Use MediaQuery.of(context).orientation to check if device is portrait or landscape.