Restrict Landscape mode in Flutter with Example

How to restrict landscape mode in Flutter:

Getting Started

Create a new Flutter project in your preferred IDE.

Open the AndroidManifest.xml file located at <project_folder>/android/app/src/main and add the following line inside the <activity> tag:

android:screenOrientation="portrait"

This will restrict the app to portrait mode only on Android devices.

Open the Info.plist file located at <project_folder>/ios/Runner and add the following lines inside the <dict> tag:

<key>UISupportedInterfaceOrientations</key>
<array>
  <string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
  <string>UIInterfaceOrientationPortrait</string>
</array>

This will restrict the app to portrait mode only on iOS devices.

Dynamically Restricting Landscape Mode

If you want to dynamically restrict landscape mode based on the screen size, follow these steps:

Define a private _getOrientation method to get the current device orientation:

Future<DeviceOrientation> _getOrientation() async {
  return await SystemChrome
      .maybeSetPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) => MediaQuery.of(context).orientation);
}

Override the initState method to call the _getOrientation method and update the preferred orientation:

@override
void initState() {
  super.initState();
  _getOrientation().then((orientation) {
    if (orientation == Orientation.landscape) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
    }
  });
}

Override the dispose method to restore the original preferred orientation:

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

That's it! You can now restrict landscape mode dynamically based on the screen size.