前言
任何一个前端平台开发无不可避免的都会遇到适配问题。
在 Flutter 中,默认是使用logical pixel逻辑像素的,系统拿到我们设的值,会自动判断在iOS或者Android上对应的尺寸,不用我们强制转换成某一个单位。
但是现在,我们希望可以与设计稿保持一致,所以需要一些解决方案。
方案一
直接使用 flutter_screenutil
库。
方案二
flutter_screenutil
是一个优秀的方案,但是写起来有一些模板代码,我希望能有一个轻量 一点的方案。
需要知道以下内容:
新版本 Flutter SDK
引入了 extension
的机制,可以对 class
进行扩展。
在 Flutter dart:ui
库下有 window
属性,可以通过它来获取屏幕的物理尺寸。
知道了这些 ,就可以开始搞事了。
核心代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import 'dart:ui';
class TLSizeFit { static double physicalWidth; static double physicalHeight; static double screenWidth; static double screenHeight; static double dpr; static double statusHeight;
static double rpx; static double px;
static void initialize({double standardSize = 750}) { physicalWidth = window.physicalSize.width; physicalHeight = window.physicalSize.height;
dpr = window.devicePixelRatio;
screenWidth = physicalWidth / dpr; screenHeight = physicalHeight / dpr;
statusHeight = window.padding.top / dpr;
rpx = screenWidth / standardSize; px = screenWidth / standardSize * 2; }
static double setRpx(double size) { return rpx * size; }
static double setPx(double size) { return px * size; } }
extension DoubleFit on double { double get px { return TLSizeFit.setPx(this); }
double get rpx { return TLSizeFit.setRpx(this); } }
extension IntFit on int { double get px { return TLSizeFit.setPx(this.toDouble()); }
double get rpx { return TLSizeFit.setRpx(this.toDouble()); } }
|
如何使用
1 2 3 4 5 6 7 8 9 10 11 12
| class DemoWidget extends StatelessWidget { @override Widget build(BuildContext context) { TLSizeFit.initialize();
return Container( width: 100.px, height: 100.px, ); } }
|
本文标题:Flutter 屏幕适配
文章作者:LeerGo
发布时间:2020-08-06
最后更新:2022-09-10
原始链接:https://blog.bugfix.fun/2020/08/06/241223bd.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 CN 许可协议。转载请注明出处!