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

Flutter应用锁定竖屏状态下如何监听设备朝向变化

方案1:使用传感器监听物理朝向(推荐,无显示影响)

MediaQuery.of(context).orientation返回的是应用自身的显示方向,你锁定竖屏后该值自然不会变化,要获取设备实际物理朝向,可以通过加速度传感器计算,不受应用方向锁定限制:

  • 先在pubspec.yaml添加依赖
dependencies:
  sensors_plus: ^4.0.1 # 可替换为最新稳定版本
  • 监听传感器事件计算朝向
import 'package:sensors_plus/sensors_plus.dart';
import 'dart:math' as math;

// 自定义物理朝向枚举
enum PhysicalOrientation {
  portraitUp,
  portraitDown,
  landscapeLeft,
  landscapeRight,
}

StreamSubscription<AccelerometerEvent>? _orientationListener;
PhysicalOrientation currentPhysicalOrientation = PhysicalOrientation.portraitUp;

void startListenOrientation() {
  // 阈值可自行调整,避免微小晃动触发误判
  const double judgeThreshold = 5.0;
  _orientationListener = accelerometerEvents.listen((event) {
    final x = event.x;
    final y = event.y;
    PhysicalOrientation newOrientation;
    if (y.abs() > x.abs()) {
      // 竖屏状态
      newOrientation = y > judgeThreshold ? PhysicalOrientation.portraitDown : PhysicalOrientation.portraitUp;
    } else {
      // 横屏状态
      newOrientation = x > judgeThreshold ? PhysicalOrientation.landscapeLeft : PhysicalOrientation.landscapeRight;
    }
    // 仅朝向变化时触发业务逻辑,减少冗余执行
    if (newOrientation != currentPhysicalOrientation) {
      currentPhysicalOrientation = newOrientation;
      // 此处添加朝向变化后的业务代码
    }
  });
}

// 页面/功能销毁时取消监听,避免内存泄漏
void stopListenOrientation() {
  _orientationListener?.cancel();
}
方案2:原生平台通道实现(无第三方依赖)

如果不想引入三方包,可以自行通过MethodChannel对接原生系统的朝向监听接口:

  • 安卓端使用OrientationEventListener获取系统朝向回调
  • iOS端监听UIDeviceOrientationDidChangeNotification通知
    原生侧拿到朝向变化后回传给Flutter即可,同样不会修改应用当前的竖屏显示规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:27:04