Futter 屏幕適配框架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 命令下載依賴
QQ截圖20201125185144.png

效果圖:

QQ圖片20201125184806.png
QQ圖片20201125184811.png
大家可以看到我們使用 flutter_ScreenUtil 框架對我們的UI進行了適配以后 我們在不通的分辨率設備 安卓模擬器和 iOS 模擬器上面顯示效果幾乎是差不多的 這樣我們就可以很好的讓我們開發的app在不同的設備得到相同的使用體驗了。

具體實現:

QQ截圖20201125190524.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,小弟在這里謝過啦 也可以加我個人QQ/微信(1693891473)

項目地址:

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

QQ 交流群:

92437359.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM