Quantcast
Viewing all articles
Browse latest Browse all 102

Answer by mikyll98 for Getting screen size in a class without buildcontext in Flutter

I previously used window singleton to retrieve the screen width and height:

double width = (window.physicalSize.shortestSide / window.devicePixelRatio);double height = (window.physicalSize.longestSide / window.devicePixelRatio);

but it was deprecated, and consequently also MediaQueryData.fromWindow() (from the accepted answer) as well.

Solution

FlutterView.physicalSize gives you

The dimensions of the rectangle into which the scene rendered in this view will be drawn on the screen, in physical pixels.

FlutterView.devicePixelRatio gives you

The number of device pixels for each logical pixel for the screen this view is displayed on.

By using the following snippet, you can then obtain the actual logical screen width and height:

FlutterView view = PlatformDispatcher.instance.views.first;double physicalWidth = view.physicalSize.width;double physicalHeight = view.physicalSize.height;double devicePixelRatio = view.devicePixelRatio;double screenWidth = physicalWidth / devicePixelRatio;double screenHeight = physicalHeight / devicePixelRatio;

Viewing all articles
Browse latest Browse all 102

Trending Articles