Futter 屏幕適配框架flutter_ScreenUtil 用法

前言 :

各位同學(xué)大家好,大家在做app開發(fā)的時候都會遇到屏幕適配的問題,安卓里面有dp iOS里面有pt 單位給我們用來處理屏幕適配 除此之外安卓還有 autosize等框架給我們使用 ,iOS也對應(yīng)屏幕適配方案給我們使用,那么在flutter 中我們可以使用 flutter_ScreenUtil 這個三方庫來處理屏幕的適配,那么廢話不多說 我們正式開始講解使用方法。

準(zhǔn)備工作:

需要安裝flutter的開發(fā)環(huán)境:大家可以去看看之前的教程:
1 win系統(tǒng)flutter開發(fā)環(huán)境安裝教程: http://m.itdecent.cn/p/152447bc8718
2 mac系統(tǒng)flutter開發(fā)環(huán)境安裝教程:http://m.itdecent.cn/p/bad2c35b41e3

安裝依賴:

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

請在pubspec.yaml 文件添加依賴 并在控制臺輸入flutter pub get 命令下載依賴


QQ截圖20201125185144.png

效果圖:

QQ圖片20201125184806.png

QQ圖片20201125184811.png

大家可以看到我們使用 flutter_ScreenUtil 框架對我們的UI進(jìn)行了適配以后 我們在不通的分辨率設(shè)備 安卓模擬器和 iOS 模擬器上面顯示效果幾乎是差不多的 這樣我們就可以很好的讓我們開發(fā)的app在不同的設(shè)備得到相同的使用體驗了。

具體實現(xiàn):

QQ截圖20201125190524.png

一般在我們正式開發(fā)當(dāng)中 UI設(shè)計那邊會給出標(biāo)注圖給我們 一般是按照某一個分辨率下面做的表示 例如(1080X1920 或者是 750*1334 之類的 )我們這邊拿到UI標(biāo)注主體要選擇web px像素做單位的視圖
然后再來使用我們的flutter_ScreenUtil 做屏幕適配:

在每個使用的地方導(dǎo)入包:

import 'package:flutter_screenutil/flutter_screenutil.dart';

屬性:

QQ截圖20201125190915.png

初始化并設(shè)置適配尺寸及字體大小是否根據(jù)系統(tǒng)的“字體大小”輔助選項來進(jìn)行縮放

在使用之前請設(shè)置好設(shè)計稿的寬度和高度,傳入設(shè)計稿的寬度和高度(單位px) 一定在MaterialApp的home中的頁面設(shè)置(即入口文件,只需設(shè)置一次),以保證在每次使用之前設(shè)置好了適配尺寸:
//填入設(shè)計稿中設(shè)備的屏幕尺寸

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  //設(shè)置適配尺寸 (填入設(shè)計稿中設(shè)備的屏幕尺寸) 此處假如設(shè)計稿是按iPhone6的尺寸設(shè)計的(iPhone6 750*1334)
  ScreenUtil.init(context,designSize: Size(750, 1334), allowFontScaling: false);
  runApp(MyApp());
}
//默認(rèn) width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.init(context);
//假如設(shè)計稿是按iPhone6的尺寸設(shè)計的(iPhone6 750*1334) 
ScreenUtil.init(context, designSize: Size(750, 1334));
//設(shè)置字體大小根據(jù)系統(tǒng)的“字體大小”輔助選項來進(jìn)行縮放,默認(rèn)為false
ScreenUtil.init(context, designSize: Size(750, 1334), allowFontScaling: true);

API

傳入設(shè)計稿的px尺寸 px px px !
  ScreenUtil().setWidth(540)  (sdk>=2.6 : 540.w) //根據(jù)屏幕寬度適配尺寸
    ScreenUtil().setHeight(200) (sdk>=2.6 : 200.h) //根據(jù)屏幕高度適配尺寸
    ScreenUtil().setSp(24)      (sdk>=2.6 : 24.sp)  //適配字體
    ScreenUtil().setSp(24, allowFontScalingSelf: true)   (sdk>=2.6 : 24.ssp) //適配字體(根據(jù)系統(tǒng)的“字體大小”輔助選項來進(jìn)行縮放)
    ScreenUtil().setSp(24, allowFontScalingSelf: false)  (sdk>=2.6 : 24.nsp) //適配字體(不會根據(jù)系統(tǒng)的“字體大小”輔助選項來進(jìn)行縮放)
    ScreenUtil().pixelRatio       //設(shè)備的像素密度
    ScreenUtil().screenWidth   (sdk>=2.6 : 1.sw)   //設(shè)備寬度
    ScreenUtil().screenHeight  (sdk>=2.6 : 1.sh)   //設(shè)備高度
    ScreenUtil().bottomBarHeight  //底部安全區(qū)距離,適用于全面屏下面有按鍵的
    ScreenUtil().statusBarHeight  //狀態(tài)欄高度 劉海屏?xí)? 單位dp
    ScreenUtil().textScaleFactor //系統(tǒng)字體縮放比例
    ScreenUtil().scaleWidth  // 實際寬度的dp與設(shè)計稿px的比例
    ScreenUtil().scaleHeight // 實際高度的dp與設(shè)計稿px的比例
    0.2.sw  //屏幕寬度的0.2倍
    0.5.sh  //屏幕高度的50%

具體使用:

 void printScreenInformation() {
    print('設(shè)備寬度:${ScreenUtil().screenWidth}'); //Device width
    print('設(shè)備高度:${ScreenUtil().screenHeight}'); //Device height
    print('設(shè)備的像素密度:${ScreenUtil().pixelRatio}'); //Device pixel density
    print(
      '底部安全區(qū)距離:${ScreenUtil().bottomBarHeight}dp',
    ); //Bottom safe zone distance,suitable for buttons with full screen
    print(
      '狀態(tài)欄高度:${ScreenUtil().statusBarHeight}dp',
    ); //Status bar height , Notch will be higher Unit px
    print('實際寬度的dp與設(shè)計稿px的比例:${ScreenUtil().scaleWidth}');
    print('實際高度的dp與設(shè)計稿px的比例:${ScreenUtil().scaleHeight}');
    print(
      '寬度和字體相對于設(shè)計稿放大的比例:${ScreenUtil().scaleWidth * ScreenUtil().pixelRatio}',
    );
    print(
      '高度相對于設(shè)計稿放大的比例:${ScreenUtil().scaleHeight * ScreenUtil().pixelRatio}',
    );
    print('系統(tǒng)的字體縮放比例:${ScreenUtil().textScaleFactor}');

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

適配尺寸

傳入設(shè)計稿的px尺寸:
根據(jù)屏幕寬度適配 width: ScreenUtil().setWidth(540),
根據(jù)屏幕高度適配 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,可以使用擴展函數(shù): example: 不用這個:

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

而是用這個:

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

適配字體:

傳入設(shè)計稿的px尺寸:

//傳入字體大小,默認(rèn)不根據(jù)系統(tǒng)的“字體大小”輔助選項來進(jìn)行縮放(可在初始化ScreenUtil時設(shè)置allowFontScaling)
ScreenUtil().setSp(28)
或
28.sp (dart sdk>=2.6)
//傳入字體大小,根據(jù)系統(tǒng)的“字體大小”輔助選項來進(jìn)行縮放(如果某個地方不遵循全局的allowFontScaling設(shè)置)       
ScreenUtil().setSp(24, allowFontScalingSelf: true)
或
24.ssp (dart sdk>=2.6)
//for example:
Column(
      crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('我的文字大小在設(shè)計稿上是24px,不會隨著系統(tǒng)的文字縮放比例變化',
             style: TextStyle(
                color: Colors.black,
               fontSize: ScreenUtil().setSp(24),
               )),
        Text('我的文字大小在設(shè)計稿上是24px,會隨著系統(tǒng)的文字縮放比例變化',
          style: TextStyle(
              color: Colors.black,
               fontSize: ScreenUtil()
             .setSp(24, allowFontScalingSelf: true))),
        ],
    )

完整代碼:

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
/**
 *
 * 創(chuàng)建人:xuqing
 * 創(chuàng)建時間: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) {
    //設(shè)置適配尺寸 (填入設(shè)計稿中設(shè)備的屏幕尺寸) 此處假如設(shè)計稿是按iPhone6的尺寸設(shè)計的(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('設(shè)備寬度:${ScreenUtil().screenWidthPx}px'),
            Text('設(shè)備高度:${ScreenUtil().screenHeightPx}px'),
            Text('設(shè)備寬度:${ScreenUtil().screenWidth}dp'),
            Text('設(shè)備高度:${ScreenUtil().screenHeight}dp'),
            Text('設(shè)備的像素密度:${ScreenUtil().pixelRatio}'),
            Text('底部安全區(qū)距離:${ScreenUtil().bottomBarHeight}dp'),
            Text('狀態(tài)欄高度:${ScreenUtil().statusBarHeight}dp'),
            Text(
              '實際寬度的dp與設(shè)計稿px的比例:${ScreenUtil().scaleWidth}',
              textAlign: TextAlign.center,
            ),
            Text(
              '實際高度的dp與設(shè)計稿px的比例:${ScreenUtil().scaleHeight}',
              textAlign: TextAlign.center,
            ),
            SizedBox(
              height: 100.h,
            ),
            Text('系統(tǒng)的字體縮放比例:${ScreenUtil().textScaleFactor}'),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '我的文字大小在設(shè)計稿上是24px,不會隨著系統(tǒng)的文字縮放比例變化',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 24.sp,
                  ),
                ),
                Text(
                  '我的文字大小在設(shè)計稿上是24px,會隨著系統(tǒng)的文字縮放比例變化',
                  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('設(shè)備寬度:${ScreenUtil().screenWidth}'); //Device width
    print('設(shè)備高度:${ScreenUtil().screenHeight}'); //Device height
    print('設(shè)備的像素密度:${ScreenUtil().pixelRatio}'); //Device pixel density
    print(
      '底部安全區(qū)距離:${ScreenUtil().bottomBarHeight}dp',
    ); //Bottom safe zone distance,suitable for buttons with full screen
    print(
      '狀態(tài)欄高度:${ScreenUtil().statusBarHeight}dp',
    ); //Status bar height , Notch will be higher Unit px

    print('實際寬度的dp與設(shè)計稿px的比例:${ScreenUtil().scaleWidth}');
    print('實際高度的dp與設(shè)計稿px的比例:${ScreenUtil().scaleHeight}');

    print(
      '寬度和字體相對于設(shè)計稿放大的比例:${ScreenUtil().scaleWidth * ScreenUtil().pixelRatio}',
    );
    print(
      '高度相對于設(shè)計稿放大的比例:${ScreenUtil().scaleHeight * ScreenUtil().pixelRatio}',
    );
    print('系統(tǒng)的字體縮放比例:${ScreenUtil().textScaleFactor}');

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

到此flutter屏幕適配三方庫 flutter_screenutil 的使用我們就講完了

最后總結(jié):

對比原生而言flutter的屏幕適配方案使用 flutter_screenutil 三方庫就比較容易實現(xiàn) 不過我們注意的是雖然我們做出來的是app但是我們使用的尺寸單位還是px 和web是一樣的 這點們要注意,以上的簡單例子只是分享給同學(xué)們 ,如果有其他更好屏幕適配方案同學(xué)們可以自己私下研究,我這邊就不展開講了。 最后希望我的文章能幫助到各位解決問題 ,以后我還會貢獻(xiàn)更多有用的代碼分享給大家。各位同學(xué)如果覺得文章還不錯 ,麻煩給關(guān)注和star,小弟在這里謝過啦

項目地址:

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容