适配步骤
1、在根目录lib新建一个utils目录,并且在下面新建size_fit.dart文件用于存放屏幕适配计算逻辑
import 'dart:ui';
class LSizeFit {
static double ?physicalWidth;
static double ?physicalHeight;
static double ?dpr;
static double ?screenWidth;
static double ?screenHeight;
static double ?statusHeight;
static double ?rpx;
static double ?px;
static void initialize({double standardSize = 700}) {
// 1. 手机物理分辨率
physicalWidth = window.physicalSize.width;
physicalHeight = window.physicalSize.height;
// 2.获取dpr
dpr = window.devicePixelRatio; // 2.5
// 3.宽度和高度
screenWidth = physicalWidth! / dpr!;
screenHeight = physicalHeight! / dpr!;
// 4.状态栏高度
statusHeight = window.padding.top / dpr!;
// 5.计算rpx和px的大小
rpx = screenWidth! / standardSize;
px = screenWidth !/ standardSize * 2;
}
static double setRpx(double size) {
return rpx!*size;
}
static double setPx(double size) {
return px!*size;
}
}
2、在main.dart中引入size_fit.dart并且在build方法中初始化LSizeFit类
部分代码
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 初始化
LSizeFit.initialize();
// TODO: implement build
return MaterialApp(
title: "适配",
home: HomePage(),
);
}
}
3、在根目录lib新建extension目录用于存放扩展包,并且在extension中新建一个double_extension.dart和一个int_extension.dart文件
double_extension.dart文件
import '../utils/size_fit.dart';
// 对double类型进行扩充
extension DoubleExtension on double {
double get rpx {
return LSizeFit.setRpx(this);
}
double get px {
return LSizeFit.setPx(this);
}
}
int_extenstion.dart文件
import '../utils/size_fit.dart';
// 对double类型进行扩充
extension IntExtension on int {
double get rpx {
return LSizeFit.setRpx(this.toDouble()); // 需要转为double类型
}
double get px {
return LSizeFit.setPx(this.toDouble());
}
}
4、在main.dart中引入extension扩展
import './extension/double_extension.dart';
import './extension/int_extension.dart';
5、使用
部分代码
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text("适配"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 400.0.rpx, // 可以通过直接.rpx转换
height: 400.rpx,
color: Colors.blue,
),
Text("字体大小适配",style: TextStyle(fontSize: 40.rpx),)
],
)
),
);
}
}
6、效果图
分辨率1080*2160下显示效果图

分辨率720*1280下显示效果图
