Shahbaz Hashmi
Shahbaz Hashmi

Reputation: 2815

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 ?

Upvotes: -1

Views: 285

Answers (2)

Ronak Punase
Ronak Punase

Reputation: 186

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.

Upvotes: 0

Shahbaz Hashmi
Shahbaz Hashmi

Reputation: 2815

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;
}

Upvotes: 0

Related Questions