Flutter屏幕适配可以采用小程序的rpx适配来完成Flutter的适配,比较好理解。
rpx适配原理:
- 不管是什么屏幕,统一分成750份
- 在iPhone5上:1rpx = 320/750 = 0.4266 ≈ 0.42px
- 在iPhone6上:1rpx = 375/750 = 0.5px
- 在iPhone6plus上:1rpx = 414/750 = 0.552px
算出一个rpx后,再将自己的size和rpx单位相乘即可:
比如100px的宽度:100 * 2 * rpx
在iPhone5上计算出的结果是84px
在iPhone6上计算出的结果是100px
在iPhone6plus上计算出的结果是110.4px
封装一个适配的工具类
import 'dart:ui';
class ScreenUtil {
static double physicalWidth;
static double physicalHeight;
static double screenWidth;
static double screenHeight;
static double dpr;
static double statusHeight;
static double rpx;
static void initialize({double standardSize = 750}) {
// 1.手机的物理分辨率
physicalWidth = window.physicalSize.width;
physicalHeight = window.physicalSize.height;
print("宽高==$physicalWidth --- $physicalHeight");
// 2.获取dpr
dpr = window.devicePixelRatio;
// 3.宽度和高度
screenWidth = physicalWidth / dpr;
screenHeight = physicalHeight / dpr;
// 4.状态栏高度
statusHeight = window.padding.top / dpr;
// 5.计算rpx的大小
rpx = screenWidth / standardSize;
}
static px(int size) {
return rpx *2 * size;
}
}
工具类的使用
首先需要在入口main.dart初始化
import 'package:flutter/material.dart';
import 'package:flutter_learn/blog/utils/screen_fit.dart';
import 'home/home_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
ScreenUtil.initialize();
return MaterialApp(
title: 'Flutter widget',
debugShowCheckedModeBanner:false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
然后直接使用工具类
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("首页"),
),
body: Stack(
children: <Widget>[
Container(
width: ScreenUtil.px(200),
height: ScreenUtil.px(200),
color: Colors.red,
),
HomePageContent(),
],
));
}
}