Flutter不同终端屏幕适配

Flutter不同终端屏幕适配

flutter_screenutil中文官方文档

1. 安装

运行命令:

1
flutter pub add flutter_screenutil

运行以上命令会在pubspec.yaml中添加:

1
2
3
dependencies:
...
flutter_screenutil: ^5.9.3

2. 封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

/// 屏幕适配工具类
class ScreenAdapter {
/// 初始化方法
static void init(BuildContext context) {
ScreenUtil.init(
context,
designSize: _getDesignSize(context),
minTextAdapt: true,
splitScreenMode: true,
);
}

/// 根据屏幕方向获取设计尺寸
static Size _getDesignSize(BuildContext context) {
final orientation = MediaQuery.of(context).orientation;
return orientation == Orientation.portrait
? const Size(375, 812) // 竖屏设计尺寸
: const Size(812, 375); // 横屏设计尺寸
}

/// 宽度适配
static double width(double width) {
return width.w;
}

/// 高度适配
static double height(double height) {
return height.h;
}

/// 字体大小适配
static double fontSize(double fontSize) {
return fontSize.sp;
}

/// 获取屏幕宽度
static double get screenWidth => Get.width;

/// 获取屏幕高度
static double get screenHeight => Get.height;

/// 设备像素比
static double get pixelRatio => Get.pixelRatio;

/// 设备类型判断
static bool get isPhone => screenWidth < 600;
static bool get isTablet => screenWidth >= 600 && screenWidth < 1024;
static bool get isDesktop => screenWidth >= 1024;

/// 响应式布局方法
static T responsive<T>({
required T phone,
T? tablet,
T? desktop,
}) {
if (isDesktop && desktop != null) return desktop;
if (isTablet && tablet != null) return tablet;
return phone;
}

/// 边距适配
static EdgeInsets padding({
double? all,
double? horizontal,
double? vertical,
double? left,
double? right,
double? top,
double? bottom,
}) {
return EdgeInsets.only(
left: (left ?? horizontal ?? all ?? 0).w,
right: (right ?? horizontal ?? all ?? 0).w,
top: (top ?? vertical ?? all ?? 0).h,
bottom: (bottom ?? vertical ?? all ?? 0).h,
);
}

/// 圆角适配
static BorderRadius radius([double radius = 0]) {
return BorderRadius.circular(radius.r);
}

/// 横竖屏切换监听(正确实现)
static void addOrientationListener(VoidCallback callback) {
// 使用 GetX 的 Workers 监听屏幕变化
ever(Get.mediaQuery as RxInterface<Object?>, (_) => callback());
}

/// 获取当前屏幕方向
static Orientation get orientation => Get.mediaQuery.orientation;
}

Flutter不同终端屏幕适配
https://jhyjhy.cn/posts/33879/
作者
jhy
发布于
2025年5月29日
许可协议