Flutter学习笔记之-获取设备信息和局部页面适配
获取设备信息
- 获取屏幕的宽高以及状态栏
// 在根节点的build方法中就可以获取
final physicalWidth = window.physicalSize.width;
final physicalHeight = window.physicalSize.height;
final dpr = window.devicePixelRatio;
final screenWidth = physicalWidth / dpr;
final screenHeight = physicalHeight / dpr;
final statusBarHeight = window.padding.top / dpr;
final bottomHeight = window.padding.bottom / dpr;
print("屏幕width:$screenWidth height:$screenHeight");
print("分辨率: $physicalWidth - $physicalHeight");
print("状态栏height: $statusBarHeight 底部高度:$bottomHeight");
print("dpr: $dpr");
- 判断平台以及获取相关信息
判断并获取平台信息
if (Platform.isIOS) {
print("numberOfProcessors = ${Platform.numberOfProcessors}");
print("localeName = ${Platform.localeName}");
print("operatingSystem = ${Platform.operatingSystem}");
print("operatingSystemVersion = ${Platform.operatingSystemVersion}");
print("localHostname = ${Platform.localHostname}");
print("environment = ${Platform.environment}");
}
获取设备信息的官方库:
device_info
屏幕适配方案
小程序中rpx的原理是什么呢?
不管是什么屏幕,统一分成750份
在iPhone5上:1rpx = 320/750 = 0.4266 ≈ 0.42px
在iPhone6上:1rpx = 375/750 = 0.5px
在iPhone6plus上:1rpx = 414/750 = 0.552px
那么我们就可以通过上面的计算方式,算出一个rpx,再将自己的size和rpx单位相乘即可:
比如100px的宽度:100 * 2 * rpx
在iPhone5上计算出的结果是84px
在iPhone6上计算出的结果是100px
在iPhone6plus上计算出的结果是110.4px
import 'dart:ui';
class ScreenFit {
static double screenWidth;
static double screenHeight;
static double rpx;
static double px;
static void initialize({double standardWidth = 750}) {
final physicalWidth = window.physicalSize.width;
final physicalHeight = window.physicalSize.height;
final dpr = window.devicePixelRatio;
screenWidth = physicalWidth / dpr;
screenHeight = physicalHeight / dpr;
rpx = screenWidth / standardWidth;
px = screenWidth / standardWidth * 2;
}
// 按照像素来设置
static double setPx(double size) {
return ScreenFit.px * size;
}
// 按照rpx来设置
static double setRpx(double size) {
return ScreenFit.rpx * size;
}
}
extension DoubleFit on double {
double get px {
return ScreenFit.setPx(this);
}
double get rpx {
return ScreenFit.setRpx(this);
}
}
extension IntFit on int {
double get px {
return ScreenFit.setPx(this.toDouble());
}
double get rpx {
return ScreenFit.setRpx(this.toDouble());
}
}