Reputation: 55
I am building a flutter application that needs precise measurements of the screen in cm / inches.
According to the docs,
By definition, there are roughly 38 logical pixels per centimeter, or about 96 logical pixels per inch, of the physical display. The value returned by devicePixelRatio is ultimately obtained either from the hardware itself, the device drivers, or a hard-coded value stored in the operating system or firmware, and may be inaccurate, sometimes by a significant margin.
I have tried using these ratios in my application but they are not even close.
Is there a way to accurately calculate the dimensions of the screen?
Upvotes: 3
Views: 7041
Reputation: 29006
You can use MediaQuery
to retrieve those fields.
final size = MediaQuery.sizeOf(context);
final pixelRatio = MediaQuery.devicePixelRatioOf(context);
// Size in logical pixels.
final width1 = size.width;
final height1 = size.height;
// Size in physical pixels.
final width2 = size.width * pixelRatio;
final height2 = size.height * pixelRatio;
Upvotes: 0
Reputation: 24781
Flutter's pixel coordinates are given in logical pixels rather than physical pixels. However, MediaQuery
will give you the conversion ratio.
var mediaQuery = MediaQuery.of(context);
var physicalPixelWidth = mediaQuery.size.width * mediaQuery.devicePixelRatio;
var physicalPixelHeight = mediaQuery.size.height * mediaQuery.devicePixelRatio;
(Note that this code can only be run in a place where a BuildContext
object is available, such as a build
method or a StatefulWidget
's companion State
class.)
Upvotes: 3