手动实现适配
import 'package:flutter/material.dart';import 'dart:ui';class Adapt {static var _layoutWidth = 750;static MediaQueryData mediaQuery = MediaQueryData.fromWindow(window);static double _width = mediaQuery.size.width;static double _height = mediaQuery.size.height;static double _topbarH = mediaQuery.padding.top;static double _botbarH = mediaQuery.padding.bottom;static double _pixelRatio = mediaQuery.devicePixelRatio;static var _ratio = _width / _layoutWidth;static px(double number){return number * _ratio;}static percent(double number) {return number * _layoutWidth * _ratio / 100;}static rem(double number) {return number * _layoutWidth * _ratio / 10;}static onepx(){return 1/_pixelRatio;}static screenW(){return _width;}static screenH(){return _height;}static padTopH(){return _topbarH;}static padBotH(){return _botbarH;}}
使用示例:
Container(width: Adapt.px(375),height: Adapt.px(750),color: Colors.blue,child: Text('设备宽度:${Adapt.px(375)}dp',style: TextStyle(color: Colors.white,fontSize: 24,),),),
- Adapt.px(100) 计算适配后的尺寸
- Adapt.onepx() 1px像素大小
flutter_screenutil
通过 flutter_screenutil (github) 包进行 flutter 屏幕适配
安装:
dependencies:flutter_screenutil: ^0.4.2
相关API:
- ScreenUtil.screenWidth 设备宽度
- ScreenUtil.screenHeight 设备高度
- ScreenUtil.pixelRatio 设备的像素密度
- ScreenUtil.bottomBarHeight 底部安全区距离
- ScreenUtil.statusBarHeight 状态栏高度
- ScreenUtil.textScaleFactory 系统的字体缩放比例
- ScreenUtil.getInstance().scaleWidth 实际宽度的dp与设计稿px的比例
- ScreenUtil.getInstance().scaleHeight 实际高度的dp与设计稿px的比例
- ScreenUtil.getInstance().setWidth(375) 按照设计稿宽度设置大小
- ScreenUtil.getInstance().setHeight(375) 按照设计稿高度设置大小
- ScreenUtil.getInstance().scaleWidth * ScreenUtil.pixelRatio 宽度和字体相对于设计稿放大的比例
- ScreenUtil.getInstance().scaleHeight * ScreenUtil.pixelRatio 高度相对于设计稿放大的比例
- ScreenUtil.getInstance().setSp(24) 设置字体大小,不会随着系统的文字缩放比例变化
- ScreenUtil(allowFontScaling: true).setSp(24) 设置字体大小,会随着系统的文字缩放比例变化
个人觉得 ScreenUtil 使用起来比较麻烦, 在我的项目中没有使用, 只是我们应该知道有那么一个东西, 或许在一些特定场景有用
