Flutter: how to prevent device orientation changes and force portrait?

I would like to prevent my application from changing its orientation and force the layout to stick to "portrait".

In the main.dart, I put:

void main(){
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  runApp(new MyApp());
}

but when I use the Android Simulator rotate buttons, the layout "follows" the new device orientation...

How could I solve this?

Thanks


Import package:flutter/services.dart, then

Put the SystemChrome.setPreferredOrientations inside the Widget build() method.

Example:

  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
      return new MaterialApp(...);
    }
  }

Update

This solution mightn't work for some IOS devices as mentioned in the updated flutter documentation on Oct 2019.

They Advise to fixed the orientation by setting UISupportedInterfaceOrientations in Info.plist like this

<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>

For more information https://github.com/flutter/flutter/issues/27235#issuecomment-508995063


@boeledi, If you want to “lock” the device orientation and not allow it to change as the user rotates their phone, this was easily set as below,

// This did not work as requirement
void main() {
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  runApp(new MyApp());
}

You have to wait until setPreferredOrientations is done and then start the app

// This will works always for lock screen Orientation.
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
    .then((_) {
      runApp(new MyApp());
    });
}

iOS:

Calling SystemChrome.setPreferredOrientations() doesn't work for me, and I had to change the Device Orientation in the Xcode project as following:

enter image description here

Android:

Set the screenOrientation attribute to portrait for the main activity in the file android/app/src/main/AndroidManifest.xml as following:

enter image description here