forked from CarGuo/gsy_github_app_flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon_utils.dart
More file actions
401 lines (368 loc) · 12.9 KB
/
common_utils.dart
File metadata and controls
401 lines (368 loc) · 12.9 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gsy_github_app_flutter/common/localization/default_localizations.dart';
import 'package:gsy_github_app_flutter/common/net/address.dart';
import 'package:gsy_github_app_flutter/common/redux/gsy_state.dart';
import 'package:gsy_github_app_flutter/common/redux/locale_redux.dart';
import 'package:gsy_github_app_flutter/common/redux/theme_redux.dart';
import 'package:gsy_github_app_flutter/common/style/gsy_string_base.dart';
import 'package:gsy_github_app_flutter/common/style/gsy_style.dart';
import 'package:gsy_github_app_flutter/common/utils/navigator_utils.dart';
import 'package:gsy_github_app_flutter/widget/gsy_flex_button.dart';
import 'package:gsy_github_app_flutter/widget/issue_edit_dIalog.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:path_provider/path_provider.dart';
import 'package:redux/redux.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_statusbar/flutter_statusbar.dart';
/**
* 通用逻辑
* Created by guoshuyu
* Date: 2018-07-16
*/
class CommonUtils {
static final double MILLIS_LIMIT = 1000.0;
static final double SECONDS_LIMIT = 60 * MILLIS_LIMIT;
static final double MINUTES_LIMIT = 60 * SECONDS_LIMIT;
static final double HOURS_LIMIT = 24 * MINUTES_LIMIT;
static final double DAYS_LIMIT = 30 * HOURS_LIMIT;
static double sStaticBarHeight = 0.0;
static void initStatusBarHeight(context) async {
sStaticBarHeight =
await FlutterStatusbar.height / MediaQuery.of(context).devicePixelRatio;
}
static String getDateStr(DateTime date) {
if (date == null || date.toString() == null) {
return "";
} else if (date.toString().length < 10) {
return date.toString();
}
return date.toString().substring(0, 10);
}
static String getUserChartAddress(String userName) {
return Address.graphicHost +
GSYColors.primaryValueString.replaceAll("#", "") +
"/" +
userName;
}
///日期格式转换
static String getNewsTimeStr(DateTime date) {
int subTime =
DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch;
if (subTime < MILLIS_LIMIT) {
return "刚刚";
} else if (subTime < SECONDS_LIMIT) {
return (subTime / MILLIS_LIMIT).round().toString() + " 秒前";
} else if (subTime < MINUTES_LIMIT) {
return (subTime / SECONDS_LIMIT).round().toString() + " 分钟前";
} else if (subTime < HOURS_LIMIT) {
return (subTime / MINUTES_LIMIT).round().toString() + " 小时前";
} else if (subTime < DAYS_LIMIT) {
return (subTime / HOURS_LIMIT).round().toString() + " 天前";
} else {
return getDateStr(date);
}
}
static getLocalPath() async {
Directory appDir;
if (Platform.isIOS) {
appDir = await getApplicationDocumentsDirectory();
} else {
appDir = await getExternalStorageDirectory();
}
PermissionStatus permission = await PermissionHandler()
.checkPermissionStatus(PermissionGroup.storage);
if (permission != PermissionStatus.granted) {
Map<PermissionGroup, PermissionStatus> permissions =
await PermissionHandler()
.requestPermissions([PermissionGroup.storage]);
if (permissions[PermissionGroup.storage] != PermissionStatus.granted) {
return null;
}
}
String appDocPath = appDir.path + "/gsygithubappflutter";
Directory appPath = Directory(appDocPath);
await appPath.create(recursive: true);
return appPath;
}
static saveImage(String url) async {
Future<String> _findPath(String imageUrl) async {
final file = await DefaultCacheManager().getSingleFile(url);
if (file == null) {
return null;
}
Directory localPath = await CommonUtils.getLocalPath();
if (localPath == null) {
return null;
}
final name = splitFileNameByPath(file.path);
final result = await file.copy(localPath.path + name);
return result.path;
}
return _findPath(url);
}
static splitFileNameByPath(String path) {
return path.substring(path.lastIndexOf("/"));
}
static getFullName(String repository_url) {
if (repository_url != null &&
repository_url.substring(repository_url.length - 1) == "/") {
repository_url = repository_url.substring(0, repository_url.length - 1);
}
String fullName = '';
if (repository_url != null) {
List<String> splicurl = repository_url.split("/");
if (splicurl.length > 2) {
fullName =
splicurl[splicurl.length - 2] + "/" + splicurl[splicurl.length - 1];
}
}
return fullName;
}
static pushTheme(Store store, int index) {
ThemeData themeData;
List<Color> colors = getThemeListColor();
themeData = getThemeData(colors[index]);
store.dispatch(new RefreshThemeDataAction(themeData));
}
static getThemeData(Color color) {
return ThemeData(primarySwatch: color, platform: TargetPlatform.android);
}
/**
* 切换语言
*/
static changeLocale(Store<GSYState> store, int index) {
Locale locale = store.state.platformLocale;
switch (index) {
case 1:
locale = Locale('zh', 'CH');
break;
case 2:
locale = Locale('en', 'US');
break;
}
store.dispatch(RefreshLocaleAction(locale));
}
static GSYStringBase getLocale(BuildContext context) {
return GSYLocalizations.of(context).currentLocalized;
}
static List<Color> getThemeListColor() {
return [
GSYColors.primarySwatch,
Colors.brown,
Colors.blue,
Colors.teal,
Colors.amber,
Colors.blueGrey,
Colors.deepOrange,
];
}
static const IMAGE_END = [".png", ".jpg", ".jpeg", ".gif", ".svg"];
static isImageEnd(path) {
bool image = false;
for (String item in IMAGE_END) {
if (path.indexOf(item) + item.length == path.length) {
image = true;
}
}
return image;
}
static copy(String data, BuildContext context) {
Clipboard.setData(new ClipboardData(text: data));
Fluttertoast.showToast(
msg: CommonUtils.getLocale(context).option_share_copy_success);
}
static launchUrl(context, String url) {
if (url == null && url.length == 0) return;
Uri parseUrl = Uri.parse(url);
bool isImage = isImageEnd(parseUrl.toString());
if (parseUrl.toString().endsWith("?raw=true")) {
isImage = isImageEnd(parseUrl.toString().replaceAll("?raw=true", ""));
}
if (isImage) {
NavigatorUtils.gotoPhotoViewPage(context, url);
return;
}
if (parseUrl != null &&
parseUrl.host == "github.com" &&
parseUrl.path.length > 0) {
List<String> pathnames = parseUrl.path.split("/");
if (pathnames.length == 2) {
//解析人
String userName = pathnames[1];
NavigatorUtils.goPerson(context, userName);
} else if (pathnames.length >= 3) {
String userName = pathnames[1];
String repoName = pathnames[2];
//解析仓库
if (pathnames.length == 3) {
NavigatorUtils.goReposDetail(context, userName, repoName);
} else {
launchWebView(context, "", url);
}
}
} else if (url != null && url.startsWith("http")) {
launchWebView(context, "", url);
}
}
static void launchWebView(BuildContext context, String title, String url) {
if (url.startsWith("http")) {
NavigatorUtils.goGSYWebView(context, url, title);
} else {
NavigatorUtils.goGSYWebView(
context,
new Uri.dataFromString(url,
mimeType: 'text/html', encoding: Encoding.getByName("utf-8"))
.toString(),
title);
}
}
static launchOutURL(String url, BuildContext context) async {
if (await canLaunch(url)) {
await launch(url);
} else {
Fluttertoast.showToast(
msg: CommonUtils.getLocale(context).option_web_launcher_error +
": " +
url);
}
}
static Future<Null> showLoadingDialog(BuildContext context) {
return NavigatorUtils.showGSYDialog(
context: context,
builder: (BuildContext context) {
return new Material(
color: Colors.transparent,
child: WillPopScope(
onWillPop: () => new Future.value(false),
child: Center(
child: new Container(
width: 200.0,
height: 200.0,
padding: new EdgeInsets.all(4.0),
decoration: new BoxDecoration(
color: Colors.transparent,
//用一个BoxDecoration装饰器提供背景图片
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Container(
child:
SpinKitCubeGrid(color: Color(GSYColors.white))),
new Container(height: 10.0),
new Container(
child: new Text(
CommonUtils.getLocale(context).loading_text,
style: GSYConstant.normalTextWhite)),
],
),
),
),
));
});
}
static Future<Null> showEditDialog(
BuildContext context,
String dialogTitle,
ValueChanged<String> onTitleChanged,
ValueChanged<String> onContentChanged,
VoidCallback onPressed, {
TextEditingController titleController,
TextEditingController valueController,
bool needTitle = true,
}) {
return NavigatorUtils.showGSYDialog(
context: context,
builder: (BuildContext context) {
return Center(
child: new IssueEditDialog(
dialogTitle,
onTitleChanged,
onContentChanged,
onPressed,
titleController: titleController,
valueController: valueController,
needTitle: needTitle,
),
);
});
}
///列表item dialog
static Future<Null> showCommitOptionDialog(
BuildContext context,
List<String> commitMaps,
ValueChanged<int> onTap, {
width = 250.0,
height = 400.0,
List<Color> colorList,
}) {
return NavigatorUtils.showGSYDialog(
context: context,
builder: (BuildContext context) {
return Center(
child: new Container(
width: width,
height: height,
padding: new EdgeInsets.all(4.0),
margin: new EdgeInsets.all(20.0),
decoration: new BoxDecoration(
color: Color(GSYColors.white),
//用一个BoxDecoration装饰器提供背景图片
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
child: new ListView.builder(
itemCount: commitMaps.length,
itemBuilder: (context, index) {
return GSYFlexButton(
maxLines: 1,
mainAxisAlignment: MainAxisAlignment.start,
fontSize: 14.0,
color: colorList != null
? colorList[index]
: Theme.of(context).primaryColor,
text: commitMaps[index],
textColor: Color(GSYColors.white),
onPress: () {
Navigator.pop(context);
onTap(index);
},
);
}),
),
);
});
}
///版本更新
static Future<Null> showUpdateDialog(
BuildContext context, String contentMsg) {
return NavigatorUtils.showGSYDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(CommonUtils.getLocale(context).app_version_title),
content: new Text(contentMsg),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: new Text(CommonUtils.getLocale(context).app_cancel)),
new FlatButton(
onPressed: () {
launch(Address.updateUrl);
Navigator.pop(context);
},
child: new Text(CommonUtils.getLocale(context).app_ok)),
],
);
});
}
}