0

i wan to change my layout from landscape to portrait and vice versa inside my app (depending on the rotation of the device by the user) in flutter

i tried using OrientationBuilder and MediaQuery but all of them read only for first time (even when user change the orientation mode) it doesn't detect the changes.

even i tried the WidgetsBindingObserver by adding:

@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}

@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}

and use didChangeMetrics() but same issue:
      @override
      void didChangeMetrics() {
        final orientation =
            WidgetsBinding.instance.window.physicalSize.aspectRatio > 1
                ? Orientation.landscape
                : Orientation.portrait;

    _currentOrientation = MediaQuery.of(context).orientation;
    print('Before Orientation Change: $_currentOrientation');
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      setState(() {
        _currentOrientation = MediaQuery.of(context).orientation;
      });
  print('After Orientation Change: $_currentOrientation');
});
}

i even tries to add setPrefrences inside the didChangeMetrics but didn't work either!

2
  • What was the thing that didn't work? When changing the orientation, are build and didChangeDependencies getting called in the widget?! Commented May 28, 2024 at 15:26
  • yes it enter for first time but when changing the orientation, it doesn't reach (doesn't print that it is now landscape for example) Commented May 29, 2024 at 11:29

1 Answer 1

0

Try this, I hope it will works

Orientation _orientation = Orientation.portrait;
      @override
      void didChangeMetrics() {
        final newOrientation = WidgetsBinding.instance.window.physicalSize.aspectRatio > 1
            ? Orientation.landscape
            : Orientation.portrait;
    
        if (newOrientation != _orientation) {
          setState(() {
            _orientation = newOrientation;
          });
        }
      }
Sign up to request clarification or add additional context in comments.

1 Comment

still not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.