skip to Main Content
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

2

Answers


  1. You have to define your default screen orientation in the main.dart like so:

    Future main() async {
       WidgetsBinding widgetsBinding = 
             WidgetsFlutterBinding.ensureInitialized();
     SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    

    when you need an other orientation on a specific screen (StatefulWidget) use this in your init method:

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

    inside the on dispose method you can set the orientation back, like this:

      @override
      dispose() {
      SystemChrome.setPreferredOrientations([
         DeviceOrientation.portraitUp,
         DeviceOrientation.portraitDown,
      ]);
      super.dispose();
      }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search