Flutter 屏幕适配之相对尺寸适配

在Android中我们可以通过脚本来动态生成适配于各个厂商的屏幕的相对尺寸。

那么在Flutter中我们如何通过相同的思路来实现同样的效果呢?我们知道,Android的每个厂商的屏幕大小存在非常大区别。有些长,有的短,有的粗,有的细,这个的确給用户提供了非常多的选择,但是对于开发来说就比较苦恼了。

那么来看看具体该怎么实现吧,其实很简单,首先我们和UI约定,UI图中的设备宽高是多少,在我们这里是宽375,高812。然后如下就是具体的实现代码,使用的方式也很简单,比如说,在UI图中,标记出是1pt的尺寸,我们完全可以通过1.pt的方式来指定其尺寸。

这里定义了两种尺寸,pt和hpt,这两个有什么区别呢?pt表示横向的尺寸,hpt表示纵向的尺寸。

请注意,如果使用这两种尺寸存在一些问题,比如遇到尺寸不是375*812的尺寸的设备那些方块的图形就会被拉伸成长方形。

对于这种情况,我们就需要将图片宽度和高度都设置成pt即可,Android本来就不同于IOS,不可能那么精准地设置每个组件的位置和大小。

Dart 复制代码
import 'dart:ui' as ui;

/// 屏幕的宽度
double get deviceWidth =>
    ui.window.physicalSize.width / ui.window.devicePixelRatio;

/// 屏幕的高度
double get deviceHeight =>
    ui.window.physicalSize.height / ui.window.devicePixelRatio;

/// 尺寸扩展,需要确保UI提供的图的高度是372*812(这个根据具体的项目而定),UI要是这么坑就砍死他
const int _physicalWidth = 375;
const int _physicalHeight = 812;

extension IntExt on int {
  ///宽度拓展
  double get pt => deviceWidth / _physicalWidth * this;

  ///高度拓展
  double get hpt => deviceHeight / _physicalHeight * this;
}
extension DoubleExt on double {
  ///宽度拓展
  double get pt => deviceWidth / _physicalWidth * this;

  ///高度拓展
  double get hpt => deviceHeight / _physicalHeight * this;
}
相关推荐
2501_946244781 天前
Flutter & OpenHarmony OA系统设置页面组件开发指南
开发语言·javascript·flutter
l134062082351 天前
Flutter Geocoding 在鸿蒙上的使用指南
flutter·华为·harmonyos
AiFlutter1 天前
三、内容展示(02):图片
flutter·低代码·低代码平台·aiflutter·aiflutter低代码
l134062082351 天前
344.在鸿蒙上使用 animations Flutter 包的指南
flutter·华为·harmonyos
2501_946244781 天前
Flutter & OpenHarmony OA系统底部导航栏组件开发指南
android·javascript·flutter
2501_944446001 天前
Flutter&OpenHarmony字体与排版设计
android·javascript·flutter
消失的旧时光-19431 天前
mixin 写一个 Flutter 的“埋点 + 日志 + 性能监控”完整框架示例
android·flutter
消失的旧时光-19431 天前
Flutter 工程中 mixin 的正确打开方式:5 种高质量设计范式 + mixin vs 继承 vs 组合 + 为什么它比 BasePage 更优雅
前端·flutter·架构
消失的旧时光-19431 天前
Flutter 中 mixin 的完整认知体系——从原理、范式、架构选择到反模式(工程实战版)
flutter·架构
2501_946244781 天前
Flutter & OpenHarmony OA系统下拉刷新组件开发指南
开发语言·javascript·flutter