1. 概述
针对各种手机的屏幕自适应是APP开发的刚性需求,本项目使用了 flutter_screenutil
版本 5.5.3+2
来实现屏幕适配,确保应用在不同尺寸的设备上都能保持良好的UI效果。
2. 初始化配置
在 main.dart
中,使用 ScreenUtilInit
包裹整个应用,并设置设计稿尺寸为 750x1334
:
return ScreenUtilInit(
designSize: Size(750, 1334),
builder: (context, child) {
return GetMaterialApp(
// 应用配置
);
});
3. 主要使用场景
3.1 尺寸适配
在 global.dart
中封装了 rpx()
方法,用于将设计稿中的尺寸转换为实际像素:
static double rpx(double rpx) {
return ScreenUtil().setWidth(2 * rpx);
}
3.2 边距处理
封装了多个边距处理方法,方便快速设置各种边距:
static EdgeInsets edge(double left, double top, double right, double bottom) {
return EdgeInsets.fromLTRB(rpx(left), rpx(top), rpx(right), rpx(bottom));
}
static EdgeInsets edgeAll(double value) {
return EdgeInsets.all(rpx(value));
}
static EdgeInsets edgeOnly({double left = 0.0, double top = 0.0, double right = 0.0, double bottom = 0.0}) {
return EdgeInsets.only(left: rpx(left), top: rpx(top), right: rpx(right), bottom: rpx(bottom));
}
static EdgeInsets edgeSymmetric({double vertical = 0.0, double horizontal = 0.0}) {
return EdgeInsets.symmetric(vertical: rpx(vertical), horizontal: rpx(horizontal));
}
4. 使用示例
4.1 设置组件尺寸
Container(
width: G.rpx(375), // 设计稿中宽度为375rpx
height: G.rpx(200), // 设计稿中高度为200rpx
)
4.2 设置边距
Padding(
padding: G.edgeAll(20), // 四周20rpx边距
child: Text('Hello World'),
)
5. 业界方案对比
5.1 Flutter官方方案 - MediaQuery
- 优点:官方支持,无需额外依赖
- 缺点:
- 需要手动计算比例,代码冗余
- 无法直接使用设计稿尺寸
- 适配逻辑分散,维护成本高
5.2 百分比布局方案
- 优点:简单直观,适合简单布局
- 缺点:
- 无法精确控制尺寸
- 复杂布局难以维护
- 无法适配不同宽高比的设备
5.3 第三方库对比
特性 | flutter_screenutil | flutter_screen | sizer |
---|---|---|---|
支持设计稿尺寸 | ✔️ | ✔️ | ✔️ |
字体适配 | ✔️ | ✔️ | ✔️ |
边距处理 | ✔️ | ✔️ | ✔️ |
状态栏高度适配 | ✔️ | ✔️ | ✔️ |
横竖屏切换支持 | ✔️ | ✔️ | ✔️ |
多语言支持 | ✔️ | ❌ | ❌ |
社区活跃度 | 高 | 中 | 低 |
6. 总结
通过 flutter_screenutil
的合理使用,本项目实现了:
- 统一的屏幕适配方案
- 便捷的尺寸转换工具
- 灵活的边距处理方法 这些措施有效保证了应用在不同设备上的UI一致性,提高了开发效率。
相比其他方案,flutter_screenutil
具有以下优势:
- 支持直接使用设计稿尺寸,减少计算成本
- 提供全面的适配功能,包括尺寸、字体、边距等
- 社区活跃,文档完善,问题解决及时
- 性能优化良好,对应用性能影响小