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

Flutter中如何将设备高度存储为全局变量?

解决Flutter全局存储设备屏幕尺寸的几种方案

方案1:单例工具类初始化

创建一个全局单例类,在App启动阶段完成屏幕尺寸初始化,后续任何文件都能直接调用:

  1. 新建device_utils.dart文件:
class DeviceUtil {
  static final DeviceUtil _instance = DeviceUtil._internal();
  factory DeviceUtil() => _instance;
  DeviceUtil._internal();

  late double screenHeight;
  late double screenWidth;

  void init(Size size) {
    screenHeight = size.height;
    screenWidth = size.width;
  }
}
  1. 在主页面的initState中完成初始化:
@override
void initState() {
  super.initState();
  final size = MediaQuery.of(context).size;
  DeviceUtil().init(size);
}
  1. 在Variables.dart或任意文件中直接使用:
// Variables.dart里直接引用
final double baseHeight = DeviceUtil().screenHeight;

方案2:在main函数中利用window对象初始化

如果不想依赖context,可以在main函数里提前获取屏幕尺寸,只需先初始化Flutter绑定:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 计算逻辑分辨率(物理尺寸/像素比)
  final size = WidgetsBinding.instance.window.physicalSize / WidgetsBinding.instance.window.devicePixelRatio;
  // 给全局变量赋值
  GlobalVariables.screenHeight = size.height;
  GlobalVariables.screenWidth = size.width;
  
  runApp(MyApp());
}

// Variables.dart中定义全局变量类
class GlobalVariables {
  static late double screenHeight;
  static late double screenWidth;
  // 其他全局变量示例
  static const primaryColor = Colors.blue;
}

方案3:结合状态管理工具(以Provider为例)

如果项目已经在用状态管理,可以把屏幕尺寸存入全局状态:

  1. 创建状态类:
class AppState extends ChangeNotifier {
  late double screenHeight;
  late double screenWidth;

  void setScreenSize(Size size) {
    screenHeight = size.height;
    screenWidth = size.width;
    notifyListeners();
  }
}
  1. 在main函数中注入Provider:
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => AppState(),
      child: MyApp(),
    ),
  );
}
  1. 在根页面初始化尺寸:
@override
void initState() {
  super.initState();
  final size = MediaQuery.of(context).size;
  Provider.of<AppState>(context, listen: false).setScreenSize(size);
}
  1. 后续在组件或相关代码中获取:
// 组件内使用
final height = Provider.of<AppState>(context).screenHeight;

// 若要在Variables.dart中使用,需确保状态已初始化后再访问,也可结合单例方式让AppState实例全局可访问

额外提示

你当前“除以常量”的适配方式比较基础,推荐结合基准设备尺寸计算缩放比例,适配会更精准:

// 以iPhone 11 Pro的高度812为基准
final scale = DeviceUtil().screenHeight / 812;
final buttonHeight = 50 * scale;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:15:40