androidflutterrotationscreen

Flutter rotate the screen


void _rotateScreen() {
    final currentOrientation = MediaQuery.of(context).orientation;

    if (currentOrientation == Orientation.portrait) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitDown,
      ]);
    } else {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
    }
    setState(() {});
  }

when i click the button screen is rotating down but if screen is down its not come again portrait up


Solution

  • In Flutter, you can use the MediaQuery class to get the current orientation of the device. However, this will only tell you if the device is in portrait or landscape mode, not the specific orientation (up, down, left, right).

    Since you are checking if the currentOrientation == Orientation.portrait every time it returns the same value, so the result is the same. Instead of that condition, I think you can:

    1. use the native_device_orientation package and do it like what you are doing.

    or

    1. You can set it manually using a boolean value and set a default (up or down). On button click, rotate the screen. Something like:
    bool isUp = false;
    
    setPortraitUp() {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
      isUp = true;
    }
    
    setPortraitDown() {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitDown,
      ]);
      isUp = false;
    }
    
    void _rotateScreen() {
      if (isUp) {
        setPortraitDown();
      } else {
        setPortraitUp();
      }
      setState(() {});
    }
    

    And you can set the default (up or down) on initState.