你可以使用这个插件
flutter_screenutil,它是一个适用于Flutter的屏幕和字体大小适配插件。让你的UI在不同的屏幕尺寸上显示合理的布局!
初始化并根据系统的“字体大小”可访问选项设置适合的大小和字体大小。请在使用前设置设计稿的宽度和高度,设计稿的宽度和高度(单位px)。一定要将页面设置在MaterialApp的home中(即入口文件,只需设置一次),以确保在每次使用前设置适合的大小。
//fill in the screen size of the device in the design
//default value : width : 1080px , height:1920px ,
allowFontScaling:false
ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
//If the design is based on the size of the iPhone6 (iPhone6 750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height:
1334)..init(context);
//If you wang to set the font size is scaled according to the system's
"font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334,
allowFontScaling: true)..init(context);
使用: #
适应屏幕尺寸: #
传递设计草稿的像素大小:
适应屏幕宽度: ScreenUtil.getInstance().setWidth(540),
适应屏幕高度: ScreenUtil.getInstance().setHeight(200),
您也可以使用ScreenUtil()代替ScreenUtil.getInstance(),例如:ScreenUtil().setHeight(200)
注意
高度也根据setWidth进行适应,以确保没有变形(当您需要正方形时)
setHeight方法主要用于高度适应,您希望控制UI上显示的高度和实际屏幕上的高度相同。
//for example:
//rectangle
Container(
width: ScreenUtil.getInstance().setWidth(375),
height: ScreenUtil.getInstance().setHeight(200),
...
),
////If you want to display a square:
Container(
width: ScreenUtil.getInstance().setWidth(300),
height: ScreenUtil.getInstance().setWidth(300),
),
适配器字体:
respect Text Size accessibility settings
ScreenUtil.getInstance().setSp(28)
Size accessibility settings
ScreenUtil(allowFontScaling: true).setSp(28)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'My font size is 24px on the design draft and will not change with the system.',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil.getInstance().setSp(24),
)),
Text(
'My font size is 24px on the design draft and will change with the system.',
style: TextStyle(
color: Colors.black,
fontSize: ScreenUtil(allowFontScaling: true).setSp(24),
)),
],
)
其他相关的APIs:
ScreenUtil.pixelRatio //Device pixel density
ScreenUtil.screenWidth //Device width
ScreenUtil.screenHeight //Device height
ScreenUtil.bottomBarHeight //Bottom safe zone distance, suitable for buttons with full screen
ScreenUtil.statusBarHeight //Status bar height , Notch will be higher Unit px
ScreenUtil.textScaleFactory //System font scaling factor
ScreenUtil.getInstance().scaleWidth //Ratio of actual width dp to design draft px
ScreenUtil.getInstance().scaleHeight //Ratio of actual height dp to design draft px