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

如何检测设备的横屏方向为landscape right还是landscape left?

检测Flutter设备的具体横屏方向

你提到的OrientationBuilder和MediaQuery.of(context).orientation确实只能区分横屏(landscape)和竖屏(portrait),无法识别具体是landscape right还是landscape left。要获取更精确的屏幕方向,可以使用MediaQuery.of(context).deviceOrientation,它会返回具体的DeviceOrientation枚举值,包含以下几种:

  • DeviceOrientation.portraitUp
  • DeviceOrientation.portraitDown
  • DeviceOrientation.landscapeLeft
  • DeviceOrientation.landscapeRight
  • DeviceOrientation.unknown

示例代码

import 'package:flutter/material.dart';

class ExactOrientationDetector extends StatefulWidget {
  const ExactOrientationDetector({super.key});

  @override
  State<ExactOrientationDetector> createState() => _ExactOrientationDetectorState();
}

class _ExactOrientationDetectorState extends State<ExactOrientationDetector> {
  @override
  Widget build(BuildContext context) {
    final currentOrientation = MediaQuery.of(context).deviceOrientation;
    String displayText = '';

    switch (currentOrientation) {
      case DeviceOrientation.portraitUp:
        displayText = '竖屏向上';
        break;
      case DeviceOrientation.portraitDown:
        displayText = '竖屏向下';
        break;
      case DeviceOrientation.landscapeLeft:
        displayText = '横屏向左';
        break;
      case DeviceOrientation.landscapeRight:
        displayText = '横屏向右';
        break;
      case DeviceOrientation.unknown:
        displayText = '未知方向';
        break;
    }

    return Scaffold(
      body: Center(
        child: Text('当前屏幕方向:$displayText', style: const TextStyle(fontSize: 20)),
      ),
    );
  }
}

关键说明

  • 必须在MaterialApp/CupertinoApp的子组件中调用MediaQuery.of(context),确保上下文包含媒体查询数据。
  • 设备方向变化时,MediaQuery会自动触发组件重建,无需手动添加监听逻辑。
  • 少数场景下设备可能返回unknown,建议提前做好兼容处理。

内容的提问来源于stack exchange,提问作者Syed Arsalan Kazmi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:07:08