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

Flutter中如何获取不受设备横竖屏方向影响的屏幕尺寸

Flutter 获取不受横竖屏切换影响的屏幕高度方案

核心原理

默认MediaQuery.of(context).size.height获取的是当前应用可视区域的逻辑高度,横竖屏切换时宽高属性会互换,所以会发生变化。要获取固定高度,我们可以直接读取设备的物理分辨率参数,通过取长边的方式规避方向切换带来的数值变化。

实现方法

方法1:通过dart:ui的Window属性直接读取(推荐)

直接读取设备物理像素尺寸,结合设备像素比计算得到固定的逻辑高度:

  • 若需要设备整个屏幕的总高度(包含状态栏、系统底部导航栏区域):
import 'dart:ui';

double getFixedScreenHeight() {
  final physicalSize = window.physicalSize;
  final devicePixelRatio = window.devicePixelRatio;
  // 取物理尺寸的长边作为固定高度(对应竖屏状态下的屏幕高度)
  final physicalHeight = max(physicalSize.width, physicalSize.height);
  return physicalHeight / devicePixelRatio;
}
  • 若需要应用可用的固定高度(排除系统状态栏、底部导航栏的占用高度,适配Flutter 3.10+):
import 'package:flutter/widgets.dart';

double getFixedAvailableHeight(BuildContext context) {
  final display = MediaQuery.of(context).display;
  final devicePixelRatio = display.devicePixelRatio;
  final physicalHeight = max(display.size.width, display.size.height);
  final totalPhysicalPadding = display.padding.top + display.padding.bottom;
  return (physicalHeight - totalPhysicalPadding) / devicePixelRatio;
}

方法2:启动时缓存固定高度

如果你的应用默认启动时是竖屏状态,可以在首帧渲染时把竖屏高度缓存到全局变量,后续直接调用即可:

// 全局变量存储固定高度
double? fixedScreenHeight;
// 全局根组件Key
final GlobalKey rootKey = GlobalKey();

void main() {
  runApp(const MyApp());
  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    final context = rootKey.currentContext;
    if (context != null) {
      fixedScreenHeight = MediaQuery.of(context).size.height;
    }
  });
}

// 根组件绑定Key
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      key: rootKey,
      // 其余配置
    );
  }
}

注意事项

  • 如果你的应用有分屏、窗口化适配需求,方法1返回的是设备整个屏幕的高度,不会随窗口大小变化,此时需要根据业务需求调整取值逻辑
  • 折叠屏设备展开/折叠状态物理尺寸会变化,此时需要监听折叠状态更新固定高度值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:18:05