您可以使用这个插件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),
)),
],
)
其他相关的API:
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