util.dart 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:math';
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter/widgets.dart';
  7. class Utils {
  8. /// 是否字符串为空
  9. static bool isEmpty(String? value) {
  10. if (value == null) {
  11. return true;
  12. }
  13. return value.isEmpty || value == 'null';
  14. }
  15. /// 字符串是否不为空
  16. static bool isNotEmpty(String? value) {
  17. return !isEmpty(value);
  18. }
  19. /// 判断邮箱
  20. static isEmail(dynamic value, {String? country = "sg"}) {
  21. switch (country) {
  22. case "sg":
  23. RegExp regExp = RegExp(r"^\w{1,}(.\w+)*@[A-z0-9]+(\.[A-z]{2,6}){1,2}$");
  24. if (regExp.hasMatch(value.toString())) {
  25. return true;
  26. } else {
  27. return false;
  28. }
  29. default:
  30. return false;
  31. }
  32. }
  33. /// 判断中国的11位手机号码
  34. static bool isChinaPhoneNumber(dynamic value) {
  35. RegExp regExp = RegExp(r"^1\d{10}$"); // 匹配以1开头的11位数字
  36. if (regExp.hasMatch(value.toString())) {
  37. return true;
  38. } else {
  39. return false;
  40. }
  41. }
  42. /// 全局的路由key
  43. static final navKey = GlobalKey<NavigatorState>();
  44. /// 全局的组件key
  45. static final widgetKey = GlobalKey<State>();
  46. //页面缓存key
  47. static dynamic pageStorageKey(dynamic keyname) {
  48. return PageStorageKey<dynamic>(keyname);
  49. }
  50. /// 关闭软键盘
  51. static void hideKeyboard(BuildContext context) {
  52. FocusScopeNode currentFocus = FocusScope.of(context);
  53. if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
  54. FocusManager.instance.primaryFocus!.unfocus();
  55. }
  56. }
  57. /// map 转 json 字符串
  58. static String encodeMap(Map<String, dynamic> mapData) {
  59. return json.encode(mapData);
  60. }
  61. /// json 字符串转 map
  62. static Map<String, dynamic> decodeJson(jsonStr) {
  63. return json.decode(jsonStr.toString());
  64. }
  65. /// 判断颜色是否是暗色还是亮色
  66. static num getComputeLuminance(Color color) {
  67. return color.computeLuminance();
  68. }
  69. /// 随机获取指定返回内的数值
  70. static int getRandomRangeInt(int min, int max) {
  71. final Random random = Random();
  72. return min + random.nextInt(max + 1 - min);
  73. }
  74. /// 无参数的防抖函数
  75. static VoidCallback debounce(
  76. VoidCallback func, [
  77. Duration delay = const Duration(milliseconds: 400),
  78. ]) {
  79. late Timer timer;
  80. return () {
  81. if (timer.isActive == true) {
  82. timer.cancel();
  83. }
  84. timer = Timer(delay, () {
  85. func.call();
  86. });
  87. };
  88. }
  89. /// 带参数的防抖函数
  90. static Function debounceArg<T>(
  91. Function func, [
  92. Duration delay = const Duration(milliseconds: 2000),
  93. ]) {
  94. late Timer timer;
  95. return (T arg) {
  96. if (timer.isActive == true) {
  97. timer.cancel();
  98. }
  99. timer = Timer(delay, () {
  100. func.call(arg);
  101. });
  102. };
  103. }
  104. /// 根据现在的小时数,返回 早上好,中午好,下午好,晚上好 这四个字符串
  105. static String formatNowGreetingText() {
  106. final now = DateTime.now();
  107. final hour = now.hour;
  108. String greeting;
  109. if (hour < 11) {
  110. greeting = '早上好';
  111. } else if (hour < 13) {
  112. greeting = '中午好';
  113. } else if (hour < 18) {
  114. greeting = '下午好';
  115. } else if (hour < 24) {
  116. greeting = '晚上好';
  117. } else {
  118. greeting = '早上好';
  119. }
  120. return greeting;
  121. }
  122. /// 将时间转化为 多久之前
  123. static String getTimeAgo(String? dateTimeStr) {
  124. if (dateTimeStr == null || dateTimeStr.isEmpty) {
  125. return 'Unknown time'; // 或者返回其他默认值
  126. }
  127. DateTime? dateTime;
  128. try {
  129. dateTime = DateTime.parse(dateTimeStr);
  130. } catch (e) {
  131. return 'Invalid date format'; // 或者返回其他默认值
  132. }
  133. if (dateTime == null) {
  134. return 'Unknown time'; // 或者返回其他默认值
  135. }
  136. final now = DateTime.now();
  137. final difference = now.difference(dateTime);
  138. if (difference.inHours < 1) {
  139. return "${difference.inMinutes} minutes ago";
  140. } else if (difference.inHours < 24) {
  141. return "${difference.inHours} hours ago";
  142. } else if (difference.inDays < 7) {
  143. return "${difference.inDays} days ago";
  144. } else if (difference.inDays < 30) {
  145. return "${(difference.inDays / 7).floor()} weeks ago";
  146. } else if (difference.inDays < 365) {
  147. return "${(difference.inDays / 30).floor()} months ago";
  148. } else {
  149. return "${(difference.inDays / 365).floor()} years ago";
  150. }
  151. }
  152. /// 从 Url 中找到对应的宽高
  153. static List<double>? extractWidthHeight(String? url) {
  154. if (isEmpty(url)) return null;
  155. // 使用正则表达式来查找形如 "宽x高" 的部分
  156. final RegExp regex = RegExp(r'-(\d+)x(\d+)\.');
  157. final matches = regex.allMatches(url!);
  158. if (matches.isNotEmpty) {
  159. // 获取最后一个匹配项
  160. final lastMatch = matches.last;
  161. final width = double.parse(lastMatch.group(1)!);
  162. final height = double.parse(lastMatch.group(2)!);
  163. return [width, height]; // 返回宽高列表
  164. }
  165. return null; // 未找到宽高
  166. }
  167. /// 将字符串的前三位和后两位显示,中间用 * 替代。
  168. static String maskString(String input) {
  169. // 检查字符串长度
  170. if (input.length <= 5) {
  171. // 如果字符串长度小于等于5,直接返回原字符串
  172. return input;
  173. }
  174. // 获取前三位和后两位
  175. String start = input.substring(0, 3);
  176. String end = input.substring(input.length - 2);
  177. // 计算中间需要的 * 的数量
  178. int asterisksCount = input.length - 5; // 计算需要的 * 的数量
  179. String asterisks = '*' * asterisksCount; // 创建 * 字符串
  180. // 拼接成新的字符串
  181. return '$start$asterisks$end';
  182. }
  183. }