ext_dart.dart 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. ViewModel中的扩展方法,用于处理网络错误
  79. */
  80. extension ControllerExtension on AutoDisposeNotifier {
  81. /// 处理Form表单的Input错误展示(专用 的我们的Api返回错误逻辑)
  82. void handleFormError(Map<String, dynamic>? json, String key, void Function(String errorStr)? callback) {
  83. if (json?.containsKey(key) == true) {
  84. String errorStrs = json![key]
  85. .map((value) {
  86. if (value is String) {
  87. return value;
  88. } else {
  89. return '';
  90. }
  91. })
  92. .toList()
  93. .join('\r\n');
  94. if (!Utils.isEmpty(errorStrs)) {
  95. callback?.call(errorStrs);
  96. }
  97. }
  98. }
  99. }
  100. // 扩展Function,添加防抖功能
  101. extension DebounceExtension on Function {
  102. void Function() debounce([int milliseconds = 500]) {
  103. Timer? _debounceTimer;
  104. return () {
  105. if (_debounceTimer?.isActive ?? false) _debounceTimer?.cancel();
  106. _debounceTimer = Timer(Duration(milliseconds: milliseconds), () {
  107. this(); //后执行
  108. });
  109. };
  110. }
  111. }
  112. // 扩展Function,添加节流功能
  113. extension ThrottleExtension on Function {
  114. void Function() throttle([int milliseconds = 500]) {
  115. bool _isAllowed = true;
  116. Timer? _throttleTimer;
  117. return () {
  118. if (!_isAllowed) return;
  119. _isAllowed = false;
  120. this(); //先执行
  121. _throttleTimer?.cancel();
  122. _throttleTimer = Timer(Duration(milliseconds: milliseconds), () {
  123. _isAllowed = true;
  124. });
  125. };
  126. }
  127. }
  128. //页面中可能要用到的扩展
  129. extension BuildContextExtensions on BuildContext {
  130. ThemeData get theme => Theme.of(this);
  131. Size get screenSize => MediaQuery.sizeOf(this);
  132. EdgeInsets get screenPadding => MediaQuery.paddingOf(this);
  133. TextScaler get screenTextScaleFactor => MediaQuery.textScalerOf(this);
  134. bool get isSmallScreen => screenSize.width < 800;
  135. bool get isMediumScreen => screenSize.width >= 800 && screenSize.width <= 1200;
  136. bool get isLargeScreen => screenSize.width > 800 && !isMediumScreen;
  137. bool get isPlatformDarkThemed => MediaQuery.platformBrightnessOf(this) == Brightness.dark;
  138. void showSnackBar(SnackBar snackBar) {
  139. ScaffoldMessenger.of(this).showSnackBar(snackBar);
  140. }
  141. void showSnackBarUsingText(String text) {
  142. final snackBar = SnackBar(
  143. content: Text(
  144. text,
  145. style: const TextStyle(color: Colors.white),
  146. ),
  147. );
  148. ScaffoldMessenger.of(this).showSnackBar(snackBar);
  149. }
  150. }