ext_dart.dart 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_riverpod/flutter_riverpod.dart';
  4. import 'package:shared/utils/screen_util.dart';
  5. import 'package:shared/utils/util.dart';
  6. /*
  7. 对象的扩展方法,模仿高阶函数
  8. */
  9. extension LetRunApply<T> on T {
  10. /// let 函数与之前的示例相同,它接受一个闭包并返回其结果。
  11. R let<R>(R Function(T) block) {
  12. return block(this);
  13. }
  14. /// run 函数也与之前的示例相同,它接受一个闭包但不返回任何内容。
  15. void run(void Function(T) block) {
  16. block(this);
  17. }
  18. /// apply 函数它接受一个闭包并在当前对象上执行该闭包。然后,它返回当前对象本身
  19. T apply(void Function(T) block) {
  20. block(this);
  21. return this;
  22. }
  23. }
  24. /*
  25. String的扩展方法,用于处理占位符
  26. */
  27. extension StringExtension on String {
  28. // 自己的校验空
  29. bool get checkEmpty {
  30. return Utils.isEmpty(this);
  31. }
  32. // 自己的校验非空
  33. bool get checkNotEmpty {
  34. return Utils.isNotEmpty(this);
  35. }
  36. // 只有一个 %s 的占位符,直接写就行
  37. String replacePlaceholder(String replacement) {
  38. String result = this;
  39. result = result.replaceFirst('%s', replacement);
  40. return result;
  41. }
  42. // 多个 %s 的占位符,使用List按顺序指定
  43. String replacePlaceholderList(List<String> replacements) {
  44. String result = this;
  45. for (int i = 0; i < replacements.length; i++) {
  46. result = result.replaceFirst('%s', replacements[i]);
  47. }
  48. return result;
  49. }
  50. // 自定义的多个占位符 ,自己写对应关系
  51. String replacePlaceholderMap(Map<String, String> replacements) {
  52. String result = this;
  53. replacements.forEach((key, value) {
  54. final pattern = RegExp(key);
  55. result = result.replaceAll(pattern, value);
  56. });
  57. return result;
  58. }
  59. //时间戳从毫秒转换为秒 13位数转换为10位数
  60. String get formartUnixTimeStamp {
  61. return substring(0, length - 3);
  62. }
  63. }
  64. /*
  65. double的扩展方法,用于ScreenUtil的扩展,主要用于容器与图片的屏幕适配
  66. */
  67. extension DoubleExtension on double {
  68. double get ap {
  69. return ScreenUtil.getInstance().getAdapterSize(this);
  70. }
  71. }
  72. extension IntExtension on int {
  73. double get ap {
  74. return ScreenUtil.getInstance().getAdapterSize(toDouble());
  75. }
  76. }
  77. /*
  78. Map的扩展方法,用于根据键提取对应值
  79. */
  80. extension MapExtension on Map<String, dynamic> {
  81. T? getValue<T>(String key, defaultValue) {
  82. return this.containsKey(key)? (this[key]!=null? (this[key] as T):(defaultValue as T)) : defaultValue as T?;
  83. }
  84. }
  85. /*
  86. Enum的扩展方法,用于将枚举转化为 字符串
  87. */
  88. extension EnumExtension on Enum {
  89. String get st {
  90. return toString().split('.').last;
  91. }
  92. }
  93. /*
  94. ViewModel中的扩展方法,用于处理网络错误
  95. */
  96. extension ControllerExtension on AutoDisposeNotifier {
  97. /// 处理Form表单的Input错误展示(专用 的我们的Api返回错误逻辑)
  98. void handleFormError(Map<String, dynamic>? json, String key, void Function(String errorStr)? callback) {
  99. if (json?.containsKey(key) == true) {
  100. String errorStrs = json![key]
  101. .map((value) {
  102. if (value is String) {
  103. return value;
  104. } else {
  105. return '';
  106. }
  107. })
  108. .toList()
  109. .join('\r\n');
  110. if (!Utils.isEmpty(errorStrs)) {
  111. callback?.call(errorStrs);
  112. }
  113. }
  114. }
  115. }
  116. // 扩展Function,添加防抖功能
  117. extension DebounceExtension on Function {
  118. void Function() debounce([int milliseconds = 500]) {
  119. Timer? _debounceTimer;
  120. return () {
  121. if (_debounceTimer?.isActive ?? false) _debounceTimer?.cancel();
  122. _debounceTimer = Timer(Duration(milliseconds: milliseconds), () {
  123. this(); //后执行
  124. });
  125. };
  126. }
  127. }
  128. // 扩展Function,添加节流功能
  129. extension ThrottleExtension on Function {
  130. void Function() throttle([int milliseconds = 500]) {
  131. bool _isAllowed = true;
  132. Timer? _throttleTimer;
  133. return () {
  134. if (!_isAllowed) return;
  135. _isAllowed = false;
  136. this(); //先执行
  137. _throttleTimer?.cancel();
  138. _throttleTimer = Timer(Duration(milliseconds: milliseconds), () {
  139. _isAllowed = true;
  140. });
  141. };
  142. }
  143. }
  144. //页面中可能要用到的扩展
  145. extension BuildContextExtensions on BuildContext {
  146. ThemeData get theme => Theme.of(this);
  147. Size get screenSize => MediaQuery.sizeOf(this);
  148. EdgeInsets get screenPadding => MediaQuery.paddingOf(this);
  149. TextScaler get screenTextScaleFactor => MediaQuery.textScalerOf(this);
  150. bool get isSmallScreen => screenSize.width < 800;
  151. bool get isMediumScreen => screenSize.width >= 800 && screenSize.width <= 1200;
  152. bool get isLargeScreen => screenSize.width > 800 && !isMediumScreen;
  153. bool get isPlatformDarkThemed => MediaQuery.platformBrightnessOf(this) == Brightness.dark;
  154. void showSnackBar(SnackBar snackBar) {
  155. ScaffoldMessenger.of(this).showSnackBar(snackBar);
  156. }
  157. void showSnackBarUsingText(String text) {
  158. final snackBar = SnackBar(
  159. content: Text(
  160. text,
  161. style: const TextStyle(color: Colors.white),
  162. ),
  163. );
  164. ScaffoldMessenger.of(this).showSnackBar(snackBar);
  165. }
  166. }