Home > Mobile >  Why does orientation == Orientation.portrait is always true although my device is already in landsca
Why does orientation == Orientation.portrait is always true although my device is already in landsca

Time:12-12

I am trying to use OrientationBuilder in flutter, but the first if statement in my code is always true.

        OrientationBuilder(
          builder: (context, orientation) {
            if (orientation == Orientation.portrait) {
              return _portraitMode();
            } else {
              return _landscapeMode();
            }
          },
        ),

I am trying to display two different things depending on the screen orientation of my phone. The problem is that, the first if statement is always true.

CodePudding user response:

To get the current orientation of your device, you can take help of the MediaQuery class and get the orientation like :-

    var currOrientation = MediaQuery.of(context).orientation

And optimise your code like so,

    return currOrientation == Orientation.potrait ? _potraitMode() : _landscapeMode();

Hope this helps!

CodePudding user response:

In such cases I would use print to debug. Just write print(orientation); and see what is being printed while you are changing device orientation

CodePudding user response:

In your code, the if statement checks if the orientation is Orientation.portrait, and if it is, it returns the _portraitMode() widget. Otherwise, it returns the _landscapeMode() widget.

If the if statement is always evaluating to true, it means that the orientation is always Orientation.portrait, and the _portraitMode() widget is always being returned. To fix this, you can check if the orientation is Orientation.landscape instead, and return the appropriate widget in that case.

Here's an example of how you could update your code to fix the issue:

    OrientationBuilder(
  builder: (context, orientation) {
    if (orientation == Orientation.landscape) {
      return _landscapeMode();
    } else {
      return _portraitMode();
    }
  },
),

Alternatively, you could use the switch statement to check the orientation and return the appropriate widget, like this:

    OrientationBuilder(
  builder: (context, orientation) {
    switch (orientation) {
      case Orientation.portrait:
        return _portraitMode();
      case Orientation.landscape:
        return _landscapeMode();
    }
  },
),

I hope that helps! Let me know if you have any other questions.

  • Related