'How to allow landscape for tablets, but prevent it on mobile phones?

I'm forcing portrait mode on mobile phones,

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

        SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
        ]);
  //...

I would like to enable landscape on Tablets (with>=600), then I tried to do something like:

  final _size = MediaQuery.of(context).size;
  if(_size.width < 600) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }

... but It doesn't work (no media query widget ancestor error)

How can I allow portrait and landscape for tablets, but force portrait on mobile phones?



Solution 1:[1]

You can try...

final data = MediaQueryData.fromWindow(WidgetsBinding.instance!.window);
if(data.size.shortestSide < 600) {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
}

It worked for me. I hope it helps someone else

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David L