本來以為Flutter的屏幕適配會(huì)挺完美之前就沒關(guān)心過,為了解決設(shè)計(jì)圖和需要的數(shù)字之間轉(zhuǎn)換問題,所以才加上了此插件
官方文檔地址 flutter_screenutil
一.插件的引用
在 pubspec.yaml 文件下新增 flutter_screenutil (注意空格問題)
dependencies:
flutter_screenutil: ^5.3.1
二.創(chuàng)建ScreenHelper
之所以在插件上再封裝是以后如果需要替換插件的時(shí)候只需要替換實(shí)現(xiàn)即可
import 'package:flutter_screenutil/flutter_screenutil.dart';
///屏幕縮放插件
class ScreenHelper {
///靜態(tài)初始化方法
static int(BuildContext context) {
ScreenUtil.init(
BoxConstraints(
maxWidth: MediaQuery.of(context).size.width,
maxHeight: MediaQuery.of(context).size.height),
designSize:Size(375, 812),//這里傳入你藍(lán)湖等上面設(shè)計(jì)圖的大小
context: context,//老版本可能不用傳這個(gè) 新版本這個(gè)必傳 要不然會(huì)報(bào)問題
orientation: Orientation.portrait);
}
static double get divider => height(2);
/// 頁(yè)面內(nèi)邊距
static EdgeInsetsGeometry get pagePadding {
return EdgeInsets.symmetric(
horizontal: pageHorizontalPadding(),
vertical: pageVerticalPadding(),
);
}
/// 頁(yè)面水平內(nèi)邊距
static pageHorizontalPadding() => width(30);
/// 頁(yè)面垂直內(nèi)邊距
static pageVerticalPadding() => width(20);
///列表item水平內(nèi)邊距
static listHorizontalPadding() => width(20);
///列表item垂直內(nèi)邊距
static listVerticalPadding() => width(30);
/// 獲取 計(jì)算后的字體
static sp(double v, {bool allowFontScalingSelf = false}) {
return v.sp;
}
/// 獲取 計(jì)算后的高度
static height(double value) {
return value.h;
}
/// 獲取 計(jì)算后的寬度
static width(double value) {
return value.w;
}
/// 獲取 計(jì)算后的屏幕高度
static double get screenHeight {
return 1.sh;
}
/// 獲取 計(jì)算后的屏幕高度
static double get screenWidth {
return 1.sw;
}
static double? get scale {
return ScreenUtil().pixelRatio;
}
static double get textScaleFactor {
return ScreenUtil().textScaleFactor;
}
///頂部導(dǎo)航欄高度= 狀態(tài)欄高度 + Appbar高度
static double get TopBarHeight {
return ScreenUtil().statusBarHeight + kToolbarHeight;
}
static double get topSafeHeight {
return ScreenUtil().statusBarHeight;
}
static double get bottomSafeHeight {
return ScreenUtil().bottomBarHeight;
}
}
三.插件初始化
官方文檔給了兩種初始化方案,
- 第一種 在main.dart中的MaterialApp外裹一層 ScreenUtilInit 官方也不建議我也沒有采用
- 第二種 在MaterialApp中啟動(dòng)的第一個(gè)界面加載int方法 (因?yàn)樗枰@取MediaQuery)
///在你第一個(gè)跳轉(zhuǎn)的頁(yè)面的build中加入即可
ScreenHelper.int(context);
四.插件的使用
//因?yàn)樯厦娑x的都是靜態(tài)方法所以直接
ScreenHelper.width(數(shù)字);
ScreenHelper.height(數(shù)字);
//上面有定義過一個(gè)頁(yè)面邊距,也可以這么用
Padding(padding: ScreenHelper.pagePadding);
五.注意事項(xiàng)
- 初始化最好是在MaterialApp下的第一個(gè)flutter頁(yè)面頁(yè)面初始化,否則調(diào)用的時(shí)候可能會(huì)報(bào)錯(cuò)
- 第二種方式 不支持在MaterialApp的theme的textTheme中使用字體適配
- 屏幕適配時(shí)候?yàn)榱吮WC統(tǒng)一 一般只選擇按一種方式適配
//按寬度適配
SizedBox(width: ScreenHelper.width(20),height: ScreenHelper.width(20),)
///按高度適配 好處是和設(shè)計(jì)圖看起來的組件高度一致
SizedBox(width: ScreenHelper.height(20),height: ScreenHelper.height(20),)
///如果混著適配大概率你是得不到正方形的 寬度高度基本上不會(huì)相等(正方形屏幕除外)
SizedBox(width: ScreenHelper.width(20),height: ScreenHelper.height(20),)