Flutter: The right way to use MediaQuery
Optimizing your flutter app for better performance is a lot tricky, that is because small mistakes can cause your app to keep rebuilding in milliseconds. and MediaQuery is one those widgets.
Here is why;
While flutter has provided multiple options for building responsive screens, MediaQuery remains the one we use the most, BUT wrongly.
Often we use MediaQuery by obtaining the whole MediaQuery instance using;
MediaQuery.of(context)
by doing this anything related to mediaQuery that changes will cause the UI to rebuild completely.
Let’s solve the problem
We can access the properties individually.
To obtain orientation
We use
MediaQuery.orientationOf(context);
To obtain screen size related data
We can use code as in below
final aspectRation = MediaQuery.sizeOf(context).aspectRatio;
final width = MediaQuery.sizeOf(context).width;
final height = MediaQuery.sizeOf(context).height;
To obtain device theme light/dark
We use
final brightness = MediaQuery.platformBrightnessOf(context);
This way only changes to what you used will cause rebuild of your widgtes.
And hey!, there are many features to explore from mediaQuery, how about you type in MediaQuery.
and wait a bit on your IDE for suggestions and some documentation guide.
MediaQuery.accessibleNavigationOf(context);
MediaQuery.alwaysUse24HourFormatOf(context);
MediaQuery.boldTextOf(context);
MediaQuery.devicePixelRatioOf(context);
MediaQuery.disableAnimationsOf(context);
MediaQuery.displayFeaturesOf(context);
MediaQuery.gestureSettingsOf(context);
MediaQuery.highContrastOf(context);
MediaQuery.invertColorsOf(context);
.....and more
I hope this will help you build better Flutter apps.
I will appreciate a clap, or even more, following me for more
#Flutter #Mobile #Responsive #Appdeveloper #flutterFreelancer #MediaQuery