Futter 屏幕适配框架flutter_ScreenUtil 用法

举报
xq9527 发表于 2022/06/09 20:50:29 2022/06/09
【摘要】 前言 :各位同学大家好,大家在做app开发的时候都会遇到屏幕适配的问题,安卓里面有dp iOS里面有pt 单位给我们用来处理屏幕适配 除此之外安卓还有 autosize等框架给我们使用 ,iOS也对应屏幕适配方案给我们使用,那么在flutter 中我们可以使用 flutter_ScreenUtil 这个三方库来处理屏幕的适配,那么废话不多说 我们正式开始讲解使用方法。 准备工作:需要安装...

前言 :

各位同学大家好,大家在做app开发的时候都会遇到屏幕适配的问题,安卓里面有dp iOS里面有pt 单位给我们用来处理屏幕适配 除此之外安卓还有 autosize等框架给我们使用 ,iOS也对应屏幕适配方案给我们使用,那么在flutter 中我们可以使用 flutter_ScreenUtil 这个三方库来处理屏幕的适配,那么废话不多说 我们正式开始讲解使用方法。

准备工作:

需要安装flutter的开发环境:大家可以去看看之前的教程:
1 win系统flutter开发环境安装教程: https://www.jianshu.com/p/152447bc8718
2 mac系统flutter开发环境安装教程:https://www.jianshu.com/p/bad2c35b41e3

安装依赖:

dependencies:
  flutter:
    sdk: flutter
  # 添加依赖
  flutter_screenutil: ^3.1.0

请在pubspec.yaml 文件添加依赖 并在控制台输入flutter pub get 命令下载依赖
6865547-f64f10c83f7cd1bc.png

效果图:

6865547-10cc8264450b3850.png
6865547-8e255d58850ea698.png
大家可以看到我们使用 flutter_ScreenUtil 框架对我们的UI进行了适配以后 我们在不通的分辨率设备 安卓模拟器和 iOS 模拟器上面显示效果几乎是差不多的 这样我们就可以很好的让我们开发的app在不同的设备得到相同的使用体验了。

具体实现:

6865547-9136ac716ad1d5a8.png
一般在我们正式开发当中 UI设计那边会给出标注图给我们 一般是按照某一个分辨率下面做的表示 例如(1080X1920 或者是 750*1334 之类的 )我们这边拿到UI标注主体要选择web px像素做单位的视图
然后再来使用我们的flutter_ScreenUtil 做屏幕适配:

在每个使用的地方导入包:

import 'package:flutter_screenutil/flutter_screenutil.dart';

属性:

QQ截图20201125190915.png

初始化并设置适配尺寸及字体大小是否根据系统的“字体大小”辅助选项来进行缩放

在使用之前请设置好设计稿的宽度和高度,传入设计稿的宽度和高度(单位px) 一定在MaterialApp的home中的页面设置(即入口文件,只需设置一次),以保证在每次使用之前设置好了适配尺寸:
//填入设计稿中设备的屏幕尺寸

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  //设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
  ScreenUtil.init(context,designSize: Size(750, 1334), allowFontScaling: false);
  runApp(MyApp());
}
//默认 width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.init(context);
//假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334) 
ScreenUtil.init(context, designSize: Size(750, 1334));
//设置字体大小根据系统的“字体大小”辅助选项来进行缩放,默认为false
ScreenUtil.init(context, designSize: Size(750, 1334), allowFontScaling: true);

API

传入设计稿的px尺寸 px px px !
  ScreenUtil().setWidth(540)  (sdk>=2.6 : 540.w) //根据屏幕宽度适配尺寸
    ScreenUtil().setHeight(200) (sdk>=2.6 : 200.h) //根据屏幕高度适配尺寸
    ScreenUtil().setSp(24)      (sdk>=2.6 : 24.sp)  //适配字体
    ScreenUtil().setSp(24, allowFontScalingSelf: true)   (sdk>=2.6 : 24.ssp) //适配字体(根据系统的“字体大小”辅助选项来进行缩放)
    ScreenUtil().setSp(24, allowFontScalingSelf: false)  (sdk>=2.6 : 24.nsp) //适配字体(不会根据系统的“字体大小”辅助选项来进行缩放)
    ScreenUtil().pixelRatio       //设备的像素密度
    ScreenUtil().screenWidth   (sdk>=2.6 : 1.sw)   //设备宽度
    ScreenUtil().screenHeight  (sdk>=2.6 : 1.sh)   //设备高度
    ScreenUtil().bottomBarHeight  //底部安全区距离,适用于全面屏下面有按键的
    ScreenUtil().statusBarHeight  //状态栏高度 刘海屏会更高  单位dp
    ScreenUtil().textScaleFactor //系统字体缩放比例
    ScreenUtil().scaleWidth  // 实际宽度的dp与设计稿px的比例
    ScreenUtil().scaleHeight // 实际高度的dp与设计稿px的比例
    0.2.sw  //屏幕宽度的0.2倍
    0.5.sh  //屏幕高度的50%

具体使用:

 void printScreenInformation() {
    print('设备宽度:${ScreenUtil().screenWidth}'); //Device width
    print('设备高度:${ScreenUtil().screenHeight}'); //Device height
    print('设备的像素密度:${ScreenUtil().pixelRatio}'); //Device pixel density
    print(
      '底部安全区距离:${ScreenUtil().bottomBarHeight}dp',
    ); //Bottom safe zone distance,suitable for buttons with full screen
    print(
      '状态栏高度:${ScreenUtil().statusBarHeight}dp',
    ); //Status bar height , Notch will be higher Unit px
    print('实际宽度的dp与设计稿px的比例:${ScreenUtil().scaleWidth}');
    print('实际高度的dp与设计稿px的比例:${ScreenUtil().scaleHeight}');
    print(
      '宽度和字体相对于设计稿放大的比例:${ScreenUtil().scaleWidth * ScreenUtil().pixelRatio}',
    );
    print(
      '高度相对于设计稿放大的比例:${ScreenUtil().scaleHeight * ScreenUtil().pixelRatio}',
    );
    print('系统的字体缩放比例:${ScreenUtil().textScaleFactor}');

    print('屏幕宽度的0.5:${0.5.sw}');
    print('屏幕高度的0.5:${0.5.sh}');
  }

适配尺寸

传入设计稿的px尺寸:
根据屏幕宽度适配 width: ScreenUtil().setWidth(540),
根据屏幕高度适配 height: ScreenUtil().setHeight(200),

 Container(
           padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
            width: ScreenUtil().setWidth(375),
           height: ScreenUtil().setHeight(200),
            color: Colors.red,
            child: Text(
             '我的宽度:${0.5.sw}dp \n'
             '我的高度:${ScreenUtil().setHeight(200)}dp',
            style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(24)),
            ),
          ),

如果你的dart sdk>=2.6,可以使用扩展函数: example: 不用这个:

Container(
width: ScreenUtil().setWidth(50),
height:ScreenUtil().setHeight(200),
)

而是用这个:

Container(
width: 50.w,
height:200.h
)

适配字体:

传入设计稿的px尺寸:

//传入字体大小,默认不根据系统的“字体大小”辅助选项来进行缩放(可在初始化ScreenUtil时设置allowFontScaling)
ScreenUtil().setSp(28)28.sp (dart sdk>=2.6)
//传入字体大小,根据系统的“字体大小”辅助选项来进行缩放(如果某个地方不遵循全局的allowFontScaling设置)       
ScreenUtil().setSp(24, allowFontScalingSelf: true)24.ssp (dart sdk>=2.6)
//for example:
Column(
      crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('我的文字大小在设计稿上是24px,不会随着系统的文字缩放比例变化',
             style: TextStyle(
                color: Colors.black,
               fontSize: ScreenUtil().setSp(24),
               )),
        Text('我的文字大小在设计稿上是24px,会随着系统的文字缩放比例变化',
          style: TextStyle(
              color: Colors.black,
               fontSize: ScreenUtil()
             .setSp(24, allowFontScalingSelf: true))),
        ],
    )

完整代码:

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
/**
 *
 * 创建人:xuqing
 * 创建时间:2020年11月25日19:22:16
 * 类说明:屏幕适配测试类
 *
 */
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter_ScreenUtil',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
    ScreenUtil.init(context, designSize: Size(750, 1334), allowFontScaling: false);
    return ExampleWidget(title: 'FlutterScreenUtil 示例');
  }
}
class ExampleWidget extends StatefulWidget {
  const ExampleWidget({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _ExampleWidgetState createState() => _ExampleWidgetState();
}
class _ExampleWidgetState extends State<ExampleWidget> {
  @override
  Widget build(BuildContext context) {
    printScreenInformation();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
                  width: ScreenUtil().setWidth(375),
                  height: ScreenUtil().setHeight(200),
                  color: Colors.red,
                  child: Text(
                    '我的宽度:${0.5.sw}dp \n'
                        '我的高度:${ScreenUtil().setHeight(200)}dp',
                    style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(24)),
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
                  width: 375.w,
                  height: 200.h,
                  color: Colors.blue,
                  child: Text(
                      '我的宽度:${375.w}dp \n'
                          '我的高度:${200.h}dp',
                      style: TextStyle(color: Colors.white, fontSize: ScreenUtil().setSp(24))),
                ),
              ],
            ),
            Text('设备宽度:${ScreenUtil().screenWidthPx}px'),
            Text('设备高度:${ScreenUtil().screenHeightPx}px'),
            Text('设备宽度:${ScreenUtil().screenWidth}dp'),
            Text('设备高度:${ScreenUtil().screenHeight}dp'),
            Text('设备的像素密度:${ScreenUtil().pixelRatio}'),
            Text('底部安全区距离:${ScreenUtil().bottomBarHeight}dp'),
            Text('状态栏高度:${ScreenUtil().statusBarHeight}dp'),
            Text(
              '实际宽度的dp与设计稿px的比例:${ScreenUtil().scaleWidth}',
              textAlign: TextAlign.center,
            ),
            Text(
              '实际高度的dp与设计稿px的比例:${ScreenUtil().scaleHeight}',
              textAlign: TextAlign.center,
            ),
            SizedBox(
              height: 100.h,
            ),
            Text('系统的字体缩放比例:${ScreenUtil().textScaleFactor}'),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '我的文字大小在设计稿上是24px,不会随着系统的文字缩放比例变化',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 24.sp,
                  ),
                ),
                Text(
                  '我的文字大小在设计稿上是24px,会随着系统的文字缩放比例变化',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 24.ssp,
                  ),
                ),
              ],
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.title),
        onPressed: () {
          ScreenUtil.init(
            context,
            designSize: Size(750, 1334),
            allowFontScaling: false,
          );
          setState(() {});
        },
      ),
    );
  }

  void printScreenInformation() {
    print('设备宽度:${ScreenUtil().screenWidth}'); //Device width
    print('设备高度:${ScreenUtil().screenHeight}'); //Device height
    print('设备的像素密度:${ScreenUtil().pixelRatio}'); //Device pixel density
    print(
      '底部安全区距离:${ScreenUtil().bottomBarHeight}dp',
    ); //Bottom safe zone distance,suitable for buttons with full screen
    print(
      '状态栏高度:${ScreenUtil().statusBarHeight}dp',
    ); //Status bar height , Notch will be higher Unit px

    print('实际宽度的dp与设计稿px的比例:${ScreenUtil().scaleWidth}');
    print('实际高度的dp与设计稿px的比例:${ScreenUtil().scaleHeight}');

    print(
      '宽度和字体相对于设计稿放大的比例:${ScreenUtil().scaleWidth * ScreenUtil().pixelRatio}',
    );
    print(
      '高度相对于设计稿放大的比例:${ScreenUtil().scaleHeight * ScreenUtil().pixelRatio}',
    );
    print('系统的字体缩放比例:${ScreenUtil().textScaleFactor}');

    print('屏幕宽度的0.5:${0.5.sw}');
    print('屏幕高度的0.5:${0.5.sh}');
  }
}

到此flutter屏幕适配三方库 flutter_screenutil 的使用我们就讲完了
##最后总结:
对比原生而言flutter的屏幕适配方案使用 flutter_screenutil 三方库就比较容易实现 不过我们注意的是虽然我们做出来的是app但是我们使用的尺寸单位还是px 和web是一样的 这点们要注意,以上的简单例子只是分享给同学们 ,如果有其他更好屏幕适配方案同学们可以自己私下研究,我这边就不展开讲了。 最后希望我的文章能帮助到各位解决问题 ,以后我还会贡献更多有用的代码分享给大家。各位同学如果觉得文章还不错 ,麻烦给关注和star,小弟在这里谢过啦

项目地址:

码云:https://gitee.com/qiuyu123/flutterscreenutil

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200