当前位置: 移动技术网 > 移动技术>移动开发>Android > Flutter 获取设备屏幕的宽高

Flutter 获取设备屏幕的宽高

2020年08月11日  | 移动技术网移动技术  | 我要评论

参看 — Flutter 中获取屏幕以及 Widget 的宽高

在移植原RN项目的过程中, 我倾向于在一开始就设置好一个全局变量来读取设备的宽高, 这在RN中很常用, 主要是为了开发方便…
在Flutter中 , 如果想用MediaQuery 媒体查询, 就势必需要依赖 WidgetsApp or MaterialApp, 也挺麻烦, 如果说仅仅需要随时随地读取一下屏幕的宽高 (iOS pt / android px), 那么用window对象也是不错的办法

 /// ------------------------------- /// Created with Flutter Dart File. /// User tianNanYiHao@163.com /// Date: 2020-08-10 /// Time: 11:26 /// Des: 用于记录一些 全局共享的基础数据 /// ------------------------------- /// import 'dart:ui'; class GlobalUtils { static num screenW; //设备的宽高 static num screenH; //设备的宽高 static num devicePixelRatio; // 设备的像素密度 static Size physicalSize; // 设备的尺寸... (px) /// 初始化设备的宽高 /// 全局记录设备的基本信息 GlobalUtils.initDeviceW_H() { // 从 window对象获取屏幕的物理尺寸(px) 及 像素密度 final physicalSize = window.physicalSize; final devicePixelRatio = window.devicePixelRatio; GlobalUtils.devicePixelRatio = devicePixelRatio; GlobalUtils.physicalSize = physicalSize; // 计算出ios/android 常用的屏幕宽高 (dp / pt); GlobalUtils.screenW = GlobalUtils.physicalSize.width / GlobalUtils.devicePixelRatio; GlobalUtils.screenH = GlobalUtils.physicalSize.height / GlobalUtils.devicePixelRatio; } } 

使用

 import 'package:ebankhome/page/CommonPage/Welcome.dart'; import 'package:ebankhome/page/home/Home.dart'; import 'package:ebankhome/router/AppRouter.dart'; import 'package:ebankhome/utils/GlobalUtils.dart'; import 'package:flutter/material.dart'; import 'dart:ui'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { // This widget is the root of your application. MyApp() { // 初始化路由 AppRouter.configureRoutes(); // 初始化尺寸的全局变量 GlobalUtils.initDeviceW_H(); } @override _MyApp createState() => _MyApp(); } class _MyApp extends State<StatefulWidget> { @override void initState() { // TODO: implement initState super.initState(); } @override Widget build(BuildContext context) { final w = GlobalUtils.screenW; final h= GlobalUtils.screenH; print('获取到的屏幕的宽度为 ------> $w'); print('获取到的屏幕的高度为 ------> $h'); return MaterialApp( title: '*******', theme: ThemeData(), //      home: Welcome(), home: Home(), // 生成路由 onGenerateRoute: AppRouter.router.generator, ); } } 
flutter: 获取到的屏幕的宽度为 ------> 414.0 flutter: 获取到的屏幕的高度为 ------> 736.0 iPhone 8 + 

本文地址:https://blog.csdn.net/iOSTianNan/article/details/107912332

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网