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
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:
or
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
.