How to force flutter device orientation for iOS

Viewed 1016

I wanna force the orientation of some pages of my application. Like, I want the orientation to be Portrait for the landing page, the options of my game, and the player selection, but I want to force the orientation to be landscape when the game begins... I tried using:

super.initState();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight,
])

and it does work on android, (except that it change the orientation 3 times before getting the right orientation...) But on iOS, it doesn't force the change... It only change when you turn the device and then it works and stays in landscape mode.

Does anyone had the same issue and know how to fix it ?

I tried to put the SystemChrome.setPreferredOrientations in the Widget build function but it didn't worked.

2 Answers

Please try this.

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

2nd Way:

await SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight
  ]);

The list of supported orientations are:

landscapeLeft
landscapeRight
portraitDown
portraitUp

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(...);
    }
  }
Related