FetFrumos
FetFrumos

Reputation: 5964

Flutter(Android): How to enable landscape orientation on a specific screen while keeping portrait as the default?

I have a Flutter application currently targeting Android. For the entire app, I want to support only portrait orientations, so I've set it up as follows (in myapp widget):

 SystemChrome.setPreferredOrientations([
  DeviceOrientation.portraitUp,
  DeviceOrientation.portraitDown,
]);

However, on one specific screen, I need to allow landscape orientation as well, with portrait being the default orientation. I've tried the following code:

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

I tried placing this code in initState and build, but it doesn't seem to work—the screen remains locked in portrait orientation.

If I use this code(in my specific screen):

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

The screen immediately switches to landscape orientation, but that's not what I want. I need the screen to default to portrait but still allow switching to landscape.

In my AndroidManifest.xml, I have the following setting:

android:screenOrientation="fullSensor"

How can I achieve this behavior where portrait is the default, but landscape is allowed on a specific screen?

Upvotes: 0

Views: 111

Answers (1)

Rico
Rico

Reputation: 370

The most important thing is to set the screenOrientation of FlutterActivity in your AndroidManifest,

android:screenOrientation="unspecified"

and make sure that the preferredOrientation of your first flutter widget is portrait-locked (default).

@override
void initState() {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
}

Then add the code on your specific screen.

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

And don't forget to restore the settings to default while this widget being disposed.

Upvotes: 0

Related Questions