在Flutter开发中也需要宽高自适应,手动写一个工具类,集成之后在像素后面直接使用 px或者 rpx即可。
工具类代码如下:
import 'dart:ui';class HYSizeFit {static double screenWidth = 0.0;static double screenHeight = 0.0;static double physicalWidth = 0.0;static double physicalHeight = 0.0;static double dpr = 0.0;static double statusHeight = 0.0;static double rpx = 0.0;static double px = 0.0;static void initialize({double standardSize = 750}) {// 1、手机的物理分辨率physicalWidth = window.physicalSize.width;physicalHeight = window.physicalSize.height;// 2、 获取dprdpr = window.devicePixelRatio;// 3、宽度和高度screenWidth = physicalWidth / dpr;screenHeight = physicalHeight / dpr;// 4、 状态栏高度statusHeight = window.padding.top / dpr;// 5、计算 rpx 的大小rpx = screenWidth / standardSize;px = screenWidth / standardSize * 2;}// 按照像素来设置static double setPx(double size) {return px * size;}// 按照rpx来设置static double setRpx(double size) {return rpx * size;}
}
扩展(extension)代码
import 'hysize.dart';extension DoubleFit on double {double get px {return HYSizeFit.setPx(this);}double get rpx {return HYSizeFit.setRpx(this);}
}extension IntFit on int {double get px {return HYSizeFit.setPx(toDouble());}double get rpx {return HYSizeFit.setRpx(toDouble());}
}
开始使用
1、需要在 main中进行初始化
Widget build(BuildContext context) {// 初始化HYSizeFit.initialize();return FlutterBoostApp(routeFactory, appBuilder: appBuilder);}
}
2、在使用的地方导入扩展文件直接使用即可
Container(width: 200.0.px,height: 200.px,
)