Flutter - Handle device orientation: layout rotate but next returns automatically to portrait

Viewed 231

I have a simple page in Flutter and I need to manage the orientation, changing the layout if portrait or landscape.

What I've done:
In my widget I added the allowed orientations for this page:

  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight
    ]);

    var screenSize = MediaQuery.of(context).size;
    final isLandscape = screenSize.width > screenSize.height;

    [...]

Now in my code I was able to manage the layout with success, using for instance something like this:

Flex(children: [
  isLandscape ? Spacer() : Container(),
[...]

or the Row() / Column() switching if needed.

What happens is that: when I rotate the device from portrait to landscape, the layout change with animation, but returns back to portrait also if the device is rotated once transition is completed.


STEP 1 -> PORTRAIT:
enter image description here


STEP 2 -> ROTATING FROM PORTRAIT TO LANDSCAPE
enter image description here


STEP 3 -> ISSUE AFTER LANDSCAPE COMPLETED
enter image description here


I have no idea on why this happens. If instead I force the orientation to portrait or landscape only, everything works well:

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

as you can see from the picture below:
enter image description here

This is the behavior on iOS, these are the iOS settings:

enter image description here

On Android instead, not rotate.

Why this happen? What I can do to avoid this?


EDIT 1:

After @PeterKoltai suggestion, I've used OrientationBuilder; is ok, rotate with success on device rotation.
The issue described here happens only if in the previous page the setPreferredOrientations is forced to portrait.
If I use the 4 orientations for each page, no issue at all, but all pages rotates...
Of course, I need to allow rotation for some pages, other must be only portraits.

0 Answers
Related