flutterorientationaspect-ratiomediaqueryflutter-ui

How to get correct and same aspect ratio of phone in landscape and portrait mode in Flutter?


I am using this code to get the aspect ratio

final deviceAspectRatio = View.of(context).physicalSize.aspectRatio;

It gives correct result in portrait but when I change the orientation in landscape and run same code I get different result. I found that width and height get flipped in orientation change so I tried

final size = View.of(context).physicalSize;
final deviceAspectRatio = isPortrait ? size.width / size.height : size.height / size.width;

but still they are not same. How can I get correct and same aspect ratio or resolution for both orientation ?


Solution

  • I found the solution. Actually in landscape mode width changes because of notch and navigation bar. So we need to use display features to get the difference.

    double _useDeviceActualAspectRatio() {
      final isPortrait = MediaQueryViewSize.isPortraitOf(useContext());
      final mediaQuery = MediaQuery.of(useContext());
      final displayFeature = mediaQuery.displayFeatures.firstOrNull;
      final width = isPortrait || displayFeature == null ? mediaQuery.size.width : mediaQuery.size.width + (displayFeature.bounds.height);
      final height = mediaQuery.size.height;
      final deviceAspectRatio = isPortrait ? width / height : height / width;
      return deviceAspectRatio;
    }