MediaQueryData returning 0.0 on some android devices for width

36 Views Asked by At

I am trying to make a tablet-only rotation. It works on iOS flawlessly, on Android however I get a width of 0.0

  print("width: " + MediaQueryData.fromWindow(WidgetsBinding.instance.window).size.width.toString());

width: 0.0

For reference, here is my entire relevant code:

Future<void> _initOrientation() async {
  if (MediaQueryData.fromWindow(WidgetsBinding.instance.window).size.width > 600) {
  //the 600 I set more or less arbitrarily, but it works well to hit what I need
    await SystemChrome.setPreferredOrientations(
      [
        DeviceOrientation.landscapeRight,
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ],
    );
  } else {
    await SystemChrome.setPreferredOrientations(
      [
        DeviceOrientation.portraitUp,
      ],
    );
  }
}

Is there anything I am doing wrong? Why does it not work for Android? Also to note - at this point in code I don't normally have BuildContext so ideally I'd have to solve it without. I couldn't think of any other elegant solution, other than moving this to a post-build context place in code but that is not ideal

Thanks!

Edit: So I tried also using WidgetsBinding

  final physicalWidth = WidgetsBinding.instance.platformDispatcher.views.first.physicalSize.width;
  final pixelRation = WidgetsBinding.instance.platformDispatcher.views.first.devicePixelRatio;
  final relativeWidthFromPhysical = physicalWidth/pixelRation;

On iOS devices it works, on my Pixel 7 and Samsung Tablet, it returns 0.

0

There are 0 best solutions below