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,
)
相关推荐
Ulyanov2 分钟前
PyVista与Tkinter桌面级3D可视化应用实战
开发语言·前端·python·3d·信息可视化·tkinter·gui开发
时光慢煮3 分钟前
Flutter 编译开发 OpenHarmony 全流程实战教程-基于开源仓库GitCode 搜索工具 v1.0.3 的跨平台实践
flutter·开源·gitcode
干前端4 分钟前
Message组件和Vue3 进阶:手动挂载组件与 Diff 算法深度解析
javascript·vue.js·算法
和你一起去月球6 分钟前
动手学Agent应用开发(TS/JS 最简实践指南)
开发语言·javascript·ecmascript·agent·mcp
小白阿龙7 分钟前
鸿蒙+flutter 跨平台开发——Placeholder 控件的基础使用场景
flutter·华为·harmonyos·鸿蒙
时光慢煮8 分钟前
基于 Flutter × OpenHarmony 图书馆管理系统之构建书籍管理模块
flutter·华为·开源·openharmony
IT陈图图8 分钟前
智慧图书馆的数字名片:基于 Flutter × OpenHarmony 的读者卡片构建实践
flutter·鸿蒙·openharmony
好大哥呀14 分钟前
Java 中的 Spring 框架
java·开发语言·spring
charlie11451419117 分钟前
输入法处理杂谈——Windows 下的 IMM32 输入法处理机制和Chrome如何桥接TSF输入法
开发语言·chrome·windows·学习·输入法
froginwe1118 分钟前
Ruby Dir 类和方法
开发语言