現(xiàn)代手機屏幕尺寸各不相同挖帘,導致我們平時寫布局的時候會在個不同的移動設(shè)備上顯示的效果不同利凑。
為了達到一套代碼所有手機體驗一致效果两嘴,需要做尺寸上的適配当编。
適配方案:
計算公式:實際尺寸 = UI尺寸 * 設(shè)備寬度/設(shè)計圖寬度
1px方案 : 1px = 1 / 設(shè)備像素比
實現(xiàn)代碼如下(以750設(shè)計圖為例):
import 'package:flutter/material.dart';
import 'dart:ui';
class Adapt {
static MediaQueryData mediaQuery = MediaQueryData.fromWindow(window);
static double _width = mediaQuery.size.width;
static double _height = mediaQuery.size.height;
static double _topbarH = mediaQuery.padding.top;
static double _botbarH = mediaQuery.padding.bottom;
static double _pixelRatio = mediaQuery.devicePixelRatio;
static var _ratio;
static init(int number){
int uiwidth = number is int ? number : 750;
_ratio = _width / uiwidth;
}
static px(number){
if(!(_ratio is double || _ratio is int)){Adapt.init(750);}
return number * _ratio;
}
static onepx(){
return 1/_pixelRatio;
}
static screenW(){
return _width;
}
static screenH(){
return _height;
}
static padTopH(){
return _topbarH;
}
static padBotH(){
return _botbarH;
}
}
解析:
1届慈、默認750設(shè)計圖
2、引入 'dart:ui' 獲得屏幕尺寸相關(guān)信息
3忿偷、計算真實像素值
使用方式:
// 設(shè)置文本大小 30 為設(shè)計圖尺寸
new Text(
'Hello World!',
style: TextStyle(
fontSize: Adapt.px(30),
)
)
// 容器尺寸大小設(shè)置 一個設(shè)計圖為 300*300像素的容器
new Container( width: Adapt.px(300),
height: Adapt.px(300),
)
// 1px
new Container(
decoration: new BoxDecoration(
border: new Border(bottom:BorderSide(width: Adapt.one())),
),
)
Adapt.px(100) 計算適配后的尺寸
Adapt.onepx() 1px像素大小