【Flutter】屏幕适配方案flutter_screenutil

345 阅读2分钟

前言

在开发flutter应用过程中,需要解决UI在不同设备上的布局问题,这里推荐使用flutter_screenutil包。 详情参看:pub-web.flutter-io.cn/packages/fl…

安装

$ flutter pub add flutter_screenutil

属性

属性类型默认值描述
designSizeSizeSize(360, 690)设计稿中设备的尺寸(单位随意,建议dp,但在使用过程中必须保持一致)
deviceSizeSizenull物理设备的大小
builderWidget Function()Container()一般返回一个MaterialApp类型的Function()
orientationOrientationportrait屏幕方向
splitScreenModeboolfalse支持分屏尺寸
minTextAdaptboolfalse是否根据宽度/高度中的最小值适配文字
contextBuildContextnull传入context会更灵敏的根据屏幕变化而改变
childWidgetnullbuilder的一部分,其依赖项属性不使用该库
rebuildFactorFunctiondefault返回屏幕指标更改时是否重建。

注意:builder和child中必须填写至少一项

初始化

使用 ScreenUtilInit 作为最顶层的组件,包裹 MaterialApp 组件


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    //Set the fit size (Find your UI design, look at the dimensions of the device screen and fill it in,unit in dp)
    return ScreenUtilInit(
      designSize: const Size(360, 690),
      minTextAdapt: true,
      splitScreenMode: true,
      // Use builder only if you need to use library outside ScreenUtilInit context
      builder: (_ , child) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'First Method',
          // You can use the library anywhere in the app even in theme
          theme: ThemeData(
            primarySwatch: Colors.blue,
            textTheme: Typography.englishLike2018.apply(fontSizeFactor: 1.sp),
          ),
          home: child,
        );
      },
      child: const HomePage(title: 'First Method'),
    );
  }
}

API

传入设计稿的dp尺寸

ScreenUtil().setWidth(540)  (dart sdk>=2.6 : 540.w)   //根据屏幕宽度适配尺寸
ScreenUtil().setHeight(200) (dart sdk>=2.6 : 200.h)   //根据屏幕高度适配尺寸(一般根据宽度适配即可)
ScreenUtil().radius(200)    (dart sdk>=2.6 : 200.r)   //根据宽度或高度中的较小者进行调整
ScreenUtil().setSp(24)      (dart sdk>=2.6 : 24.sp)   //适配字体
12.sm   // 取12和12.sp中的最小值

ScreenUtil.pixelRatio       //设备的像素密度
ScreenUtil.screenWidth   (dart sdk>=2.6 : 1.sw)   //设备宽度
ScreenUtil.screenHeight  (dart sdk>=2.6 : 1.sh)   //设备高度
ScreenUtil.bottomBarHeight  //底部安全区距离,适用于全面屏下面有按键的
ScreenUtil.statusBarHeight  //状态栏高度 刘海屏会更高
ScreenUtil.textScaleFactor //系统字体缩放比例

ScreenUtil().scaleWidth  // 实际宽度设计稿宽度的比例
ScreenUtil().scaleHeight // 实际高度与设计稿高度度的比例

ScreenUtil().orientation  //屏幕方向

0.2.sw  //屏幕宽度的0.2倍
0.5.sh  //屏幕高度的50%
20.setVerticalSpacing  // SizedBox(height: 20 * scaleHeight)
20.horizontalSpace  // SizedBox(height: 20 * scaleWidth)
const RPadding.all(8)   // Padding.all(8.r) - 获取到const的优点
EdgeInsets.all(10).w    //EdgeInsets.all(10.w)
REdgeInsets.all(8)       // EdgeInsets.all(8.r)
EdgeInsets.only(left:8,right:8).r // EdgeInsets.only(left:8.r,right:8.r).
BoxConstraints(maxWidth: 100, minHeight: 100).w    //BoxConstraints(maxWidth: 100.w, minHeight: 100.w)
Radius.circular(16).w          //Radius.circular(16.w)
BorderRadius.all(Radius.circular(16)).w