utils.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. import 'dart:convert';
  2. import 'package:barcode_scan/barcode_scan.dart';
  3. import 'package:crypto/crypto.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter/services.dart';
  6. import 'package:liftmanager/utils/theme_utils.dart';
  7. import 'package:liftmanager/utils/toast.dart';
  8. import 'package:keyboard_actions/keyboard_actions.dart';
  9. import 'package:url_launcher/url_launcher.dart';
  10. import 'package:liftmanager/utils/url.dart';
  11. import 'package:liftmanager/common/user_db.dart';
  12. import 'package:liftmanager/internal/account/model/user_entity.dart';
  13. import "package:intl/intl.dart";
  14. class Utils {
  15. // 根据关键字获取当前用户角色是否有该功能
  16. static bool getAuthByRouter(String router, [bool isAbnormal = true]) {
  17. List<AppMenus> userAuth = User().getUserAuth();
  18. bool flag = false;
  19. for (int i = 0; i < userAuth.length; i++) {
  20. print(userAuth[i].router);
  21. if (userAuth[i].router == router) {
  22. flag = true;
  23. break;
  24. }
  25. }
  26. // return true;
  27. if (flag) {
  28. return true;
  29. } else {
  30. if (isAbnormal) {
  31. toasts('暂无权限,请先开通会员!');
  32. }
  33. return false;
  34. }
  35. }
  36. // 图片异常处理
  37. static String getImagePath(String url,{bool isWater = false}) {
  38. RegExp exp = RegExp(r"(http|https):\/\/([\w.]+\/?)\S*");
  39. String endImg = "?x-oss-process=image/watermark,size_60,t_40,g_center,rotate_30,color_FFFFFF,text_5Zu-54mH5p2l5rqQIOKAnOeUteair-euoeWutuKAnQ==";
  40. if (url == null || url == "") {
  41. return "";
  42. } else {
  43. if (exp.hasMatch(url)) {
  44. if(isWater){
  45. return url + endImg;
  46. }else {
  47. return url;
  48. }
  49. } else {
  50. if(isWater){
  51. return imgFontUrl + url + endImg;
  52. }else {
  53. return imgFontUrl + url;
  54. }
  55. }
  56. }
  57. }
  58. // md5 加密
  59. static String generateMd5(String str) {
  60. return md5.convert(utf8.encode(str)).toString();
  61. }
  62. /// 调起拨号页
  63. static void launchTelURL(String phone) async {
  64. String url = 'tel:' + phone;
  65. if (await canLaunch(url)) {
  66. await launch(url);
  67. } else {
  68. toasts('拨号失败!');
  69. }
  70. }
  71. /// 调起二维码扫描页
  72. static Future<String> scan() async {
  73. try {
  74. return await BarcodeScanner.scan();
  75. } catch (e) {
  76. if (e is PlatformException) {
  77. if (e.code == BarcodeScanner.CameraAccessDenied) {
  78. toasts("没有相机权限!");
  79. }
  80. }
  81. }
  82. return null;
  83. }
  84. static KeyboardActionsConfig getKeyboardActionsConfig(
  85. BuildContext context, List<FocusNode> list) {
  86. return KeyboardActionsConfig(
  87. keyboardActionsPlatform: KeyboardActionsPlatform.IOS,
  88. keyboardBarColor: ThemeUtils.getKeyboardActionsColor(context),
  89. nextFocus: true,
  90. actions: List.generate(
  91. list.length,
  92. (i) => KeyboardAction(
  93. focusNode: list[i],
  94. closeWidget: const Padding(
  95. padding: const EdgeInsets.all(5.0),
  96. child: const Text("关闭"),
  97. ),
  98. )),
  99. );
  100. }
  101. static String getFileType(String fileName) {
  102. fileName = fileName.toLowerCase();
  103. var index1 = fileName.lastIndexOf(".");
  104. var index2 = fileName.length;
  105. var fileType = fileName.substring(index1, index2);
  106. switch (fileType) {
  107. case ".jpg":
  108. case ".jpeg":
  109. case ".jpe":
  110. case ".png":
  111. case ".bmp":
  112. case ".gif":
  113. return "image";
  114. case ".pdf":
  115. return "pdf";
  116. case ".json":
  117. return "json";
  118. case ".svg":
  119. case ".svgz":
  120. return "svg";
  121. case ".mp3":
  122. return "audio";
  123. case ".mp4":
  124. return "video";
  125. case ".mov":
  126. return "video";
  127. case ".htm":
  128. case ".html":
  129. return "html";
  130. case ".css":
  131. return "css";
  132. case ".csv":
  133. return "csv";
  134. case ".txt":
  135. case ".text":
  136. case ".conf":
  137. case ".def":
  138. case ".log":
  139. case ".in":
  140. return "plain";
  141. }
  142. return null;
  143. }
  144. static final DateFormat _monthFormat = new DateFormat("yyyy年MM月");
  145. static final DateFormat _dayFormat = new DateFormat("dd");
  146. static final DateFormat _firstDayFormat = new DateFormat("MMM dd");
  147. static final DateFormat _fullDayFormat = new DateFormat("EEE MMM dd, yyyy");
  148. static final DateFormat _apiDayFormat = new DateFormat("yyyy-MM-dd");
  149. static String formatMonth(DateTime d) => _monthFormat.format(d);
  150. static String formatDay(DateTime d) => _dayFormat.format(d);
  151. static String formatFirstDay(DateTime d) => _firstDayFormat.format(d);
  152. static String fullDayFormat(DateTime d) => _fullDayFormat.format(d);
  153. static String apiDayFormat(DateTime d) => _apiDayFormat.format(d);
  154. static const List<String> weekdays = const [
  155. "日",
  156. "一",
  157. "二",
  158. "三",
  159. "四",
  160. "五",
  161. "六"
  162. ];
  163. static List<DateTime> daysInMonth(DateTime month) {
  164. var first = firstDayOfMonth(month);
  165. var daysBefore = first.weekday;
  166. var firstToDisplay = first.subtract(new Duration(days: daysBefore));
  167. var last = Utils.lastDayOfMonth(month);
  168. var daysAfter = 7 - last.weekday;
  169. // If the last day is sunday (7) the entire week must be rendered
  170. if (daysAfter == 0) {
  171. daysAfter = 7;
  172. }
  173. var lastToDisplay = last.add(new Duration(days: daysAfter));
  174. return daysInRange(firstToDisplay, lastToDisplay).toList();
  175. }
  176. static bool isFirstDayOfMonth(DateTime day) {
  177. return isSameDay(firstDayOfMonth(day), day);
  178. }
  179. static bool isLastDayOfMonth(DateTime day) {
  180. return isSameDay(lastDayOfMonth(day), day);
  181. }
  182. static DateTime firstDayOfMonth(DateTime month) {
  183. return new DateTime(month.year, month.month);
  184. }
  185. static DateTime firstDayOfWeek(DateTime day) {
  186. /// Handle Daylight Savings by setting hour to 12:00 Noon
  187. /// rather than the default of Midnight
  188. day = new DateTime.utc(day.year, day.month, day.day, 12);
  189. /// Weekday is on a 1-7 scale Monday - Sunday,
  190. /// This Calendar works from Sunday - Monday
  191. var decreaseNum = day.weekday % 7;
  192. return day.subtract(new Duration(days: decreaseNum));
  193. }
  194. static DateTime lastDayOfWeek(DateTime day) {
  195. /// Handle Daylight Savings by setting hour to 12:00 Noon
  196. /// rather than the default of Midnight
  197. day = new DateTime.utc(day.year, day.month, day.day, 12);
  198. /// Weekday is on a 1-7 scale Monday - Sunday,
  199. /// This Calendar's Week starts on Sunday
  200. var increaseNum = day.weekday % 7;
  201. return day.add(new Duration(days: 7 - increaseNum));
  202. }
  203. /// The last day of a given month
  204. static DateTime lastDayOfMonth(DateTime month) {
  205. var beginningNextMonth = (month.month < 12)
  206. ? new DateTime(month.year, month.month + 1, 1)
  207. : new DateTime(month.year + 1, 1, 1);
  208. return beginningNextMonth.subtract(new Duration(days: 1));
  209. }
  210. /// Returns a [DateTime] for each day the given range.
  211. ///
  212. /// [start] inclusive
  213. /// [end] exclusive
  214. static Iterable<DateTime> daysInRange(DateTime start, DateTime end) sync* {
  215. var i = start;
  216. var offset = start.timeZoneOffset;
  217. while (i.isBefore(end)) {
  218. yield i;
  219. i = i.add(new Duration(days: 1));
  220. var timeZoneDiff = i.timeZoneOffset - offset;
  221. if (timeZoneDiff.inSeconds != 0) {
  222. offset = i.timeZoneOffset;
  223. i = i.subtract(new Duration(seconds: timeZoneDiff.inSeconds));
  224. }
  225. }
  226. }
  227. /// Whether or not two times are on the same day.
  228. static bool isSameDay(DateTime a, DateTime b) {
  229. return a.year == b.year && a.month == b.month && a.day == b.day;
  230. }
  231. static bool isSameWeek(DateTime a, DateTime b) {
  232. /// Handle Daylight Savings by setting hour to 12:00 Noon
  233. /// rather than the default of Midnight
  234. a = new DateTime.utc(a.year, a.month, a.day);
  235. b = new DateTime.utc(b.year, b.month, b.day);
  236. var diff = a.toUtc().difference(b.toUtc()).inDays;
  237. if (diff.abs() >= 7) {
  238. return false;
  239. }
  240. var min = a.isBefore(b) ? a : b;
  241. var max = a.isBefore(b) ? b : a;
  242. var result = max.weekday % 7 - min.weekday % 7 >= 0;
  243. return result;
  244. }
  245. static DateTime previousMonth(DateTime m) {
  246. var year = m.year;
  247. var month = m.month;
  248. if (month == 1) {
  249. year--;
  250. month = 12;
  251. } else {
  252. month--;
  253. }
  254. return new DateTime(year, month);
  255. }
  256. static DateTime nextMonth(DateTime m) {
  257. var year = m.year;
  258. var month = m.month;
  259. if (month == 12) {
  260. year++;
  261. month = 1;
  262. } else {
  263. month++;
  264. }
  265. return new DateTime(year, month);
  266. }
  267. static DateTime previousWeek(DateTime w) {
  268. return w.subtract(new Duration(days: 7));
  269. }
  270. static DateTime nextWeek(DateTime w) {
  271. return w.add(new Duration(days: 7));
  272. }
  273. }
  274. /// 默认dialog背景色为半透明黑色,这里修改源码改为透明
  275. Future<T> showTransparentDialog<T>({
  276. @required BuildContext context,
  277. bool barrierDismissible = true,
  278. WidgetBuilder builder,
  279. }) {
  280. final ThemeData theme = Theme.of(context, shadowThemeOnly: true);
  281. return showGeneralDialog(
  282. context: context,
  283. pageBuilder: (BuildContext buildContext, Animation<double> animation,
  284. Animation<double> secondaryAnimation) {
  285. final Widget pageChild = Builder(builder: builder);
  286. return SafeArea(
  287. child: Builder(builder: (BuildContext context) {
  288. return theme != null
  289. ? Theme(data: theme, child: pageChild)
  290. : pageChild;
  291. }),
  292. );
  293. },
  294. barrierDismissible: barrierDismissible,
  295. barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
  296. barrierColor: const Color(0x00FFFFFF),
  297. transitionDuration: const Duration(milliseconds: 150),
  298. transitionBuilder: _buildMaterialDialogTransitions,
  299. );
  300. }
  301. Widget _buildMaterialDialogTransitions(
  302. BuildContext context,
  303. Animation<double> animation,
  304. Animation<double> secondaryAnimation,
  305. Widget child) {
  306. return FadeTransition(
  307. opacity: CurvedAnimation(
  308. parent: animation,
  309. curve: Curves.easeOut,
  310. ),
  311. child: child,
  312. );
  313. }
  314. Future<T> showElasticDialog<T>({
  315. @required BuildContext context,
  316. bool barrierDismissible = true,
  317. WidgetBuilder builder,
  318. }) {
  319. final ThemeData theme = Theme.of(context, shadowThemeOnly: true);
  320. return showGeneralDialog(
  321. context: context,
  322. pageBuilder: (BuildContext buildContext, Animation<double> animation,
  323. Animation<double> secondaryAnimation) {
  324. final Widget pageChild = Builder(builder: builder);
  325. return SafeArea(
  326. child: Builder(builder: (BuildContext context) {
  327. return theme != null
  328. ? Theme(data: theme, child: pageChild)
  329. : pageChild;
  330. }),
  331. );
  332. },
  333. barrierDismissible: barrierDismissible,
  334. barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
  335. barrierColor: Colors.black54,
  336. transitionDuration: const Duration(milliseconds: 550),
  337. transitionBuilder: _buildDialogTransitions,
  338. );
  339. }
  340. Widget _buildDialogTransitions(
  341. BuildContext context,
  342. Animation<double> animation,
  343. Animation<double> secondaryAnimation,
  344. Widget child) {
  345. return FadeTransition(
  346. opacity: CurvedAnimation(
  347. parent: animation,
  348. curve: Curves.easeOut,
  349. ),
  350. child: SlideTransition(
  351. position: Tween<Offset>(begin: const Offset(0.0, 0.3), end: Offset.zero)
  352. .animate(CurvedAnimation(
  353. parent: animation,
  354. curve: animation.status != AnimationStatus.forward
  355. ? Curves.easeOutBack
  356. : ElasticOutCurve(0.85),
  357. )),
  358. child: child,
  359. ),
  360. );
  361. }
  362. // Color string2Color(String colorString){
  363. // int value = 0x00000000;
  364. // if(isNotEmpty(colorString)){
  365. // if(colorString[0] == "#"){
  366. // colorString = colorString.substring(1);
  367. // }
  368. // value = int.tryParse(colorString,raidx:16);
  369. // if(value != null){
  370. // if(value < 0xFF000000){
  371. // value += 0xFF000000;
  372. // }
  373. // }
  374. // }
  375. // return Color(value);
  376. // }