How to prevent device rotation only for certain classes in Flutter?

1,034

You can try using something like this in your widget:

// to lock in landscape view
@override
void initState() {
  super.initState();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeRight,
    DeviceOrientation.landscapeLeft,
  ]);
}

@override
dispose() {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeRight,
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  super.dispose();
}

The fact that initState() and dispose() are used means that you have to use a StatefulWidget if that wasn't the case already.

Share:
1,034
Ale TheFe
Author by

Ale TheFe

I'm a professional FrontEnd Developer, skilled on mobile development (I love Flutter) and in desktop development (React). I've been working as a FullStack dev for many years, so I'm capable to code in PHP and I'm studying Elixir to improve my skills

Updated on December 17, 2022

Comments

  • Ale TheFe
    Ale TheFe over 1 year

    I'm developing a Flutter app, and I need to prevent the device rotation only in some classes, while keeping it working in others. I now how to disable the rotation globally in the app, but how to disable it only in certain classes?