Flutter – Managing the MediaQuery Object
Last Updated :
15 Dec, 2021
During the process of developing an app for both phones and tablets, it is standard practice to have different UI layouts for different screen sizes for a better user experience. If the user has a preference set for different font sizes or wants to curtail animations. This is where MediaQuery comes into action, you can get information about the current device size, as well as user preferences, and design your layout accordingly. MediaQuery provides a higher-level view of the current app’s screen size and can also give more detailed information about the device and its layout preferences. In practice, MediaQuery is always there. It can simply be accessed by calling MediaQuery.of in the build method.
From there you can look up all sorts of interesting information about the device you’re running on, like the size of the screen, and build your layout accordingly. MediaQuery can also be used to check the current device’s orientation or can be used to check if the user has modified the default font size. It can also be used to determine if parts of the screen are obscured by a system UI, similar to a safe area widget.
Example:
Using mediaQuery.of automatically causes the widgets to rebuild themselves according to the current device sizes and layout preferences every time they change.
Dart
class Home extends StatelessWidget {
var size,height,width;
@override
Widget build(BuildContext context) {
size = MediaQuery.of(context).size;
height = size.height;
width = size.width;
return Scaffold(
appBar: AppBar(
title: Text( "Geeks For Geeks" ),
backgroundColor: Colors.green,
),
body: Container(
color: Colors.yellow,
height: height/2,
width: width/2,
),
);
}
}
|
Output:
Example 2: Getting device orientation and rebuilding accordingly.
Dart
class Home extends StatelessWidget {
var orientation, size,height,width;
@override
Widget build(BuildContext context) {
orientation = MediaQuery.of(context).orientation;
size = MediaQuery.of(context).size;
height = size.height;
width = size.width;
return Scaffold(
appBar: AppBar(
title: Text( "Geeks For Geeks" ),
backgroundColor: Colors.green,
),
body: orientation == Orientation.portrait?Container(
color: Colors.blue,
height: height/4,
width: width/4,
):Container(
height: height/3,
width: width/3,
color: Colors.red,
),
);
}
}
|
Output:
Note: You can change the orientation by putting these code before the runApp() in your main.dart file
Dart
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(MyHomePage());
}
|
Share your thoughts in the comments
Please Login to comment...