screen_util.dart
8.28 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
* Created by 李卓原 on 2018/9/29.
* email: zhuoyuan93@gmail.com
*/
import 'dart:math' show min, max;
import 'dart:ui' as ui show FlutterView;
import 'package:flutter/widgets.dart';
typedef FontSizeResolver = double Function(num fontSize, ScreenUtil instance);
class ScreenUtil {
static const Size defaultSize = Size(360, 690);
static ScreenUtil _instance = ScreenUtil._();
/// UI设计中手机尺寸 , dp
/// Size of the phone in UI Design , dp
late Size _uiSize;
///屏幕方向
late Orientation _orientation;
late bool _minTextAdapt;
late MediaQueryData _data;
late bool _splitScreenMode;
FontSizeResolver? fontSizeResolver;
ScreenUtil._();
factory ScreenUtil() => _instance;
/// Manually wait for window size to be initialized
///
/// `Recommended` to use before you need access window size
/// or in custom splash/bootstrap screen [FutureBuilder]
///
/// example:
/// ```dart
/// ...
/// ScreenUtil.init(context, ...);
/// ...
/// FutureBuilder(
/// future: Future.wait([..., ensureScreenSize(), ...]),
/// builder: (context, snapshot) {
/// if (snapshot.hasData) return const HomeScreen();
/// return Material(
/// child: LayoutBuilder(
/// ...
/// ),
/// );
/// },
/// )
/// ```
static Future<void> ensureScreenSize([
ui.FlutterView? window,
Duration duration = const Duration(milliseconds: 10),
]) async {
final binding = WidgetsFlutterBinding.ensureInitialized();
binding.deferFirstFrame();
await Future.doWhile(() {
if (window == null) {
window = binding.platformDispatcher.implicitView;
}
if (window == null || window!.physicalSize.isEmpty) {
return Future.delayed(duration, () => true);
}
return false;
});
binding.allowFirstFrame();
}
Set<Element>? _elementsToRebuild;
/// ### Experimental
/// Register current page and all its descendants to rebuild.
/// Helpful when building for web and desktop
static void registerToBuild(
BuildContext context, [
bool withDescendants = false,
]) {
(_instance._elementsToRebuild ??= {}).add(context as Element);
if (withDescendants) {
context.visitChildren((element) {
registerToBuild(element, true);
});
}
}
static void configure({
MediaQueryData? data,
Size? designSize,
bool? splitScreenMode,
bool? minTextAdapt,
FontSizeResolver? fontSizeResolver,
}) {
try {
if (data != null)
_instance._data = data;
else
data = _instance._data;
if (designSize != null)
_instance._uiSize = designSize;
else
designSize = _instance._uiSize;
} catch (_) {
throw Exception(
'You must either use ScreenUtil.init or ScreenUtilInit first');
}
final MediaQueryData? deviceData = data.nonEmptySizeOrNull();
final Size deviceSize = deviceData?.size ?? designSize;
final orientation = deviceData?.orientation ??
(deviceSize.width > deviceSize.height
? Orientation.landscape
: Orientation.portrait);
_instance
..fontSizeResolver = fontSizeResolver ?? _instance.fontSizeResolver
.._minTextAdapt = minTextAdapt ?? _instance._minTextAdapt
.._splitScreenMode = splitScreenMode ?? _instance._splitScreenMode
.._orientation = orientation;
_instance._elementsToRebuild?.forEach((el) => el.markNeedsBuild());
}
/// Initializing the library.
static void init(
BuildContext context, {
Size designSize = defaultSize,
bool splitScreenMode = false,
bool minTextAdapt = false,
FontSizeResolver? fontSizeResolver,
}) {
return configure(
data: MediaQuery.maybeOf(context),
designSize: designSize,
splitScreenMode: splitScreenMode,
minTextAdapt: minTextAdapt,
fontSizeResolver: fontSizeResolver,
);
}
static Future<void> ensureScreenSizeAndInit(
BuildContext context, {
Size designSize = defaultSize,
bool splitScreenMode = false,
bool minTextAdapt = false,
FontSizeResolver? fontSizeResolver,
}) {
return ScreenUtil.ensureScreenSize().then((_) {
return configure(
data: MediaQuery.maybeOf(context),
designSize: designSize,
minTextAdapt: minTextAdapt,
splitScreenMode: splitScreenMode,
fontSizeResolver: fontSizeResolver,
);
});
}
///获取屏幕方向
///Get screen orientation
Orientation get orientation => _orientation;
/// 每个逻辑像素的字体像素数,字体的缩放比例
/// The number of font pixels for each logical pixel.
double get textScaleFactor => _data.textScaleFactor;
/// 设备的像素密度
/// The size of the media in logical pixels (e.g, the size of the screen).
double? get pixelRatio => _data.devicePixelRatio;
/// 当前设备宽度 dp
/// The horizontal extent of this size.
double get screenWidth => _data.size.width;
///当前设备高度 dp
///The vertical extent of this size. dp
double get screenHeight => _data.size.height;
/// 状态栏高度 dp 刘海屏会更高
/// The offset from the top, in dp
double get statusBarHeight => _data.padding.top;
/// 底部安全区距离 dp
/// The offset from the bottom, in dp
double get bottomBarHeight => _data.padding.bottom;
/// 实际尺寸与UI设计的比例
/// The ratio of actual width to UI design
double get scaleWidth => screenWidth / _uiSize.width;
/// The ratio of actual height to UI design
double get scaleHeight =>
(_splitScreenMode ? max(screenHeight, 700) : screenHeight) /
_uiSize.height;
double get scaleText =>
_minTextAdapt ? min(scaleWidth, scaleHeight) : scaleWidth;
/// 根据UI设计的设备宽度适配
/// 高度也可以根据这个来做适配可以保证不变形,比如你想要一个正方形的时候.
/// Adapted to the device width of the UI Design.
/// Height can also be adapted according to this to ensure no deformation ,
/// if you want a square
double setWidth(num width) => width * scaleWidth;
/// 根据UI设计的设备高度适配
/// 当发现UI设计中的一屏显示的与当前样式效果不符合时,
/// 或者形状有差异时,建议使用此方法实现高度适配.
/// 高度适配主要针对想根据UI设计的一屏展示一样的效果
/// Highly adaptable to the device according to UI Design
/// It is recommended to use this method to achieve a high degree of adaptation
/// when it is found that one screen in the UI design
/// does not match the current style effect, or if there is a difference in shape.
double setHeight(num height) => height * scaleHeight;
///根据宽度或高度中的较小值进行适配
///Adapt according to the smaller of width or height
double radius(num r) => r * min(scaleWidth, scaleHeight);
/// Adapt according to the both width and height
double diagonal(num d) => d * scaleHeight * scaleWidth;
/// Adapt according to the maximum value of scale width and scale height
double diameter(num d) => d * max(scaleWidth, scaleHeight);
///字体大小适配方法
///- [fontSize] UI设计上字体的大小,单位dp.
///Font size adaptation method
///- [fontSize] The size of the font on the UI design, in dp.
double setSp(num fontSize) =>
fontSizeResolver?.call(fontSize, _instance) ?? fontSize * scaleText;
SizedBox setVerticalSpacing(num height) =>
SizedBox(height: setHeight(height));
SizedBox setVerticalSpacingFromWidth(num height) =>
SizedBox(height: setWidth(height));
SizedBox setHorizontalSpacing(num width) => SizedBox(width: setWidth(width));
SizedBox setHorizontalSpacingRadius(num width) =>
SizedBox(width: radius(width));
SizedBox setVerticalSpacingRadius(num height) =>
SizedBox(height: radius(height));
SizedBox setHorizontalSpacingDiameter(num width) =>
SizedBox(width: diameter(width));
SizedBox setVerticalSpacingDiameter(num height) =>
SizedBox(height: diameter(height));
SizedBox setHorizontalSpacingDiagonal(num width) =>
SizedBox(width: diagonal(width));
SizedBox setVerticalSpacingDiagonal(num height) =>
SizedBox(height: diagonal(height));
}
extension on MediaQueryData? {
MediaQueryData? nonEmptySizeOrNull() {
if (this?.size.isEmpty ?? true)
return null;
else
return this;
}
}