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

Flutter iOS16 设备旋转异常问题求助

Flutter iOS16 设备旋转后自动恢复原方向问题解决

在Flutter中通过按钮触发设备旋转,指定单一方向后立刻调用SystemChrome.setPreferredOrientations([])开放所有方向,iOS16以下正常,但iOS16中旋转完成后会带动画恢复到原方向。

原触发代码:

SystemChrome.setPreferredOrientations(
  _isPortrait
      ? [
          DeviceOrientation.landscapeRight,
        ]
      : [
          DeviceOrientation.portraitUp,
        ],
).then((value) {
  SystemChrome.setPreferredOrientations([]);
});

原因分析

iOS16对屏幕方向的生命周期管理做了调整,当你在强制旋转的Future回调里立刻重置允许的方向时,系统还未完全完成当前旋转状态的确认,导致触发自动恢复逻辑。

解决方法

方法1:延迟重置允许的方向

给系统足够时间完成旋转动画和状态同步,再开放所有方向:

await SystemChrome.setPreferredOrientations(
  _isPortrait
      ? [DeviceOrientation.landscapeRight]
      : [DeviceOrientation.portraitUp],
);
// 延迟300ms,可根据实际设备动画时长调整
await Future.delayed(const Duration(milliseconds: 300));
SystemChrome.setPreferredOrientations([]);

方法2:监听设备方向变化,确认目标方向后再重置

通过WidgetsBinding监听方向变化,当设备实际方向变为目标方向时,再开放所有方向:

final targetOrientation = _isPortrait 
    ? DeviceOrientation.landscapeRight 
    : DeviceOrientation.portraitUp;

// 先强制旋转到目标方向
await SystemChrome.setPreferredOrientations([targetOrientation]);

// 监听方向变化流,直到匹配目标方向
final binding = WidgetsBinding.instance;
await for (final orientation in binding.window.onOrientationChanged) {
  if (orientation == targetOrientation) {
    SystemChrome.setPreferredOrientations([]);
    break;
  }
}

额外注意事项

  • 确保iOS项目的Info.plist中已添加所有需要支持的屏幕方向(比如竖屏、横屏左右),避免系统层面的方向限制。
  • 检查页面或路由是否设置了preferredOrientation,这类配置可能会覆盖全局的方向设置。

内容的提问来源于stack exchange,提问作者Gyeom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:20:37