屏幕适配之后,为不同设备的DPI提供相同的大小,需要用到 flutter_screenutil 插件

flutter pub add flutter_screenutil

修改app.dart

app.dart
import 'package:e_book_clone/pges/home.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

Size get designSize {
final firstView = WidgetsBinding.instance.platformDispatcher.views.first;
// 逻辑短边
final logicalShortestSide =
firstView.physicalSize.shortestSide / firstView.devicePixelRatio;
// 逻辑长边
final logicalLongestSide =
firstView.physicalSize.longestSide / firstView.devicePixelRatio;
// 缩放比例 designSize越小,元素越大
const scaleFactor = 0.95;
return Size(
logicalShortestSide * scaleFactor, logicalLongestSide * scaleFactor);
}

class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ScreenUtilInit(
designSize: designSize,
builder: (context, child) {
return MaterialApp(
theme: ThemeData(
useMaterial3: true,
),
home: const HomePage(),
);
},
);
}
}

使用案例

import 'package:flutter_screenutil/flutter_screenutil.dart';
TextStyle(fontSize: 18.sp),
Container(
width: 15.w,
height: 15.h,
padding: EdgeInsets.all(15.r),
margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h, bottom: 15.h),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(12.r)),
)