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,
)
相关推荐
kyle~19 小时前
计算机系统 --- 缓存一致性
开发语言·c++·缓存·计算机系统
李妍.1 天前
02Numpy基础(上)
开发语言·python
TheBestRucy1 天前
Python 九阳神功之贰:面向对象(下)
开发语言·python
AI_小站1 天前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
felixking1 天前
C++20 协程
开发语言·c++·协程
Zane1994121 天前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言
码农颜1 天前
6.3 主函数流程剖析
开发语言·php
TheBestRucy1 天前
Python 九阳神功:从零筑基到线程飞升
服务器·开发语言·网络·人工智能·python
研☆香1 天前
聊一聊前端的常见字 关键字
开发语言·前端·javascript
草莓橙子碗1 天前
Claude 使用指南
开发语言·python