Flutter iOS - MediaQuery.of(context).size.width does not give the width in pixel

1,901

According to the docs for MediaQuery.of(context).size,

MediaQuery.of(context).size returns the size of the media in logical pixels

Logical pixels are roughly the same visual size across devices. Physical pixels are the size of the actual hardware pixels on the device. The number of physical pixels per logical pixel is described by the devicePixelRatio.

What is being displayed to you by Flutter are the logical pixels of your devices. What you are probably looking for (or terming as 640 pixels and 1125 pixels) are the physical pixels of the devices.

To get the physical pixels of the devices, you should try

var devicePhysicalPixelWidth = MediaQuery.of(context).size.width * MediaQuery.of(context).devicePixelRatio

which is in simple terms, devicePhysicalPixelWidth = logical pixel width * device pixel ratio

Share:
1,901
Simon B
Author by

Simon B

Updated on December 16, 2022

Comments

  • Simon B
    Simon B over 1 year

    I'm writing a new flutter app and at some point, I need to get the number of pixel of an iOS device. When I use the MediaQuery.of(context).size.width it returns the number of pixel divided by 3 or 2 depending on the device I'm using.

    For exemple, on my iPhone5s, the screen width is suppose to be 640 pixels, but the media query returns me 320. And on my iPhoneXs, the width is suppose to be 1125 pixels, but it returns me 375.

    How do we fix the problem ? I'm not sure but I heard apple was not working with pixels but with a system of point ? It might be related...