現代手機屏幕尺寸各不相同,導致我們平時寫布局的時候會在個不同的移動設備上顯示的效果不同。

為了達到一套代碼所有手機體驗一致效果,需要做尺寸上的適配。

適配方案:

計算公式:實際尺寸 = UI尺寸 * 設備寬度/設計圖寬度

1px方案 : 1px = 1 / 設備像素比

實現代碼如下(以750設計圖為例):

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設計圖

2、引入 dart:ui 獲得屏幕尺寸相關信息

3、計算真實像素值

使用方式:

// 設置文本大小 30 為設計圖尺寸
new Text(
Hello World!,
style: TextStyle(
fontSize: Adapt.px(30),
)
)

// 容器尺寸大小設置 一個設計圖為 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像素大小

推薦我開發的Flutter App Demo:

wangweianger/FlutterApp

推薦閱讀:

相关文章