Search code examples
flutterscreen-orientationdevice-orientation

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

  • 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