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
相关产品推荐
相关产品推荐

