Flutter 宽高自适应

在Flutter开发中也需要宽高自适应,手动写一个工具类,集成之后在像素后面直接使用 px或者 rpx即可。

工具类代码如下:

dart 复制代码
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、 获取dpr
    dpr = 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)代码

dart 复制代码
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中进行初始化

dart 复制代码
  @override
  Widget build(BuildContext context) {
    // 初始化
    HYSizeFit.initialize();
    return FlutterBoostApp(routeFactory, appBuilder: appBuilder);
  }
}

2、在使用的地方导入扩展文件直接使用即可

dart 复制代码
Container(
    width: 200.0.px,
    height: 200.px,
)
相关推荐
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
三十而立洋2 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
卡布鲁2 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
李少兄2 天前
JavaScript 隐式全局变量解析
javascript
霍霍的袁2 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超2 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int2 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
沙蒿同学2 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端