You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter屏幕旋转功能异常:点击按钮仅能向下旋转无法恢复向上

解决Flutter屏幕旋转无法恢复纵向向上的问题

你的代码核心问题在于:Orientation.portrait是一个包含portraitUp和portraitDown两种状态的笼统枚举值。当屏幕处于portraitDown时,currentOrientation == Orientation.portrait依然成立,导致代码重复设置portraitDown,永远触发不了切换到portraitUp的逻辑。

要解决这个问题,需要直接判断精确的设备方向,而非使用宽泛的Orientation分类。修改后的代码如下:

void _rotateScreen() {
  final currentDeviceOrientation = MediaQuery.of(context).deviceOrientation;

  if (currentDeviceOrientation == DeviceOrientation.portraitUp) {
    // 从纵向向上切换到纵向向下
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
    ]);
  } else {
    // 从纵向向下切换回纵向向上
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
  }
  setState(() {});
}

修改后,每次点击按钮都会基于当前设备的精确方向执行切换逻辑,即可正常在portraitUp和portraitDown之间来回切换。

内容的提问来源于stack exchange,提问作者Yunus Emre Çakmak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:14:51