Derpington
Derpington

Reputation: 109

Proper use of MediaQuery in Flutter

What is the best practice for using MediaQuery? The app will be used in different screen sizes, so hard-coding the width and height of a widget might be a problem.

I'm having a hard time understanding the different uses of the MediaQuery class. I tried searching for it online, but I didn't find many examples. It would be great if anyone can help me to understand this class or can provide a link that I can use to understand this MediaQuery class.

Upvotes: 4

Views: 7486

Answers (1)

Miha
Miha

Reputation: 14948

A few points there will be:

  • For instance, MediaQuery.of(context).size.width - will not give you the exact width in pixels for your physical device measurements but rather in logical pixels. To get the exact physical device measurements you need to do something like this: MediaQuery.of(context).size.width * MediaQuery.of(context).devicePixelRatio
    • MediaQuery.of(context).padding.top is the height of the status bar
    • kToolbarHeight is the height of the AppBar
    • in case you have a BottomNavigation bar, the height is kBottomNavigationBarHeight.

So, to deduct all the values above, we can do like this: MediaQuery.of(context).size.height — MediaQuery.of(context).padding.top — kToolbarHeight — kBottomNavigationBarHeight

I've put this tutorial together some time ago, if you are still looking for an answer to your question. Widgets sizes relative to screen size in Flutter using MediaQuery. I hope it helps!

Upvotes: 4

Related Questions