BenSabo
BenSabo

Reputation: 551

Get width and height of the device in Flutter

I need a reliable way to get the dimensions of the screen.

I know MediaQuery.of(context), but it removes the bottom padding when the bottom UI item is visible.

Upvotes: 10

Views: 6243

Answers (2)

nukeolay
nukeolay

Reputation: 11

Recently I've published plugin, that can help you to get the dimensions of the screen, and other display metrics, such as PPI and diagonal, also it will help you to convert inches & cm to Flutter logical pixels. You can try it here https://pub.dev/packages/display_metrics

Upvotes: 0

rmtmckenzie
rmtmckenzie

Reputation: 40433

This appears to be impossible from within dart at the moment on Android due to flutter ignoring the bottom system UI (i.e. the buttons).

I thought this might be a bug, but if you look closely at the documentation it never states that window.physicalSize or MediaQueryData.size are the physical dimensions of the screen, but rather the size to which flutter can render. That probably makes sense, or else every single app would have to make sure to take that into account.

So what you're going to have to do is use method channels to communicate with android directly. I took a look already and there doesn't appear to be any plugins doing this, so you could wrap it up into one if you feel ambitious. But what you'll want to do is make a call to native and then get the physical screen size directly in java code. If you do that you'd probably be best off implementing it for iOS as well, although this same problem doesn't exist there (you could even do it directly in flutter with an if/else).

Luckily, someone has done this before so you can use it as an example: https://github.com/magnatronus/flutter-displaymetrics. Assuming that displayMetrics gives you the right size.

Hope that helps and sorry I don't have a simpler answer for you!

Upvotes: 9

Related Questions