Flutter学习笔记之-获取设备信息和局部页面适配

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());
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值