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

63 views Asked by At

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 ?

2

There are 2 answers

0
Shahbaz Hashmi On

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;
}
0
Ronak Punase On

Try using the flipped getter on physicalSize.

@override
Widget build(BuildContext context) {
return Scaffold(
  body: OrientationBuilder(builder: (context, Orientation orientation) {
    double aspectRatio;
    if (orientation.name == "portrait") {
      aspectRatio = View.of(context).physicalSize.aspectRatio;
    } else {
      aspectRatio = View.of(context).physicalSize.flipped.aspectRatio;
    }
    return Center(
      child: Text(
        "Aspect Ratio: $aspectRatio",
      ),
    );
  }),
);
}

The aspectRatio is not exactly the same, but it is pretty close.