base_expand.dart 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import 'dart:async';
  2. import 'dart:ui';
  3. extension TrimAllExtension on String {
  4. String trimAll() {
  5. return replaceAll(RegExp(r'\s+'), '');
  6. }
  7. String trimAndReduceSpaces() {
  8. return trim().replaceAll(RegExp(r'\s+'), ' ');
  9. }
  10. }
  11. extension FutureMap<T> on Future<T> {
  12. Future<R> map<R>(R Function(T) transform) {
  13. return then(transform);
  14. }
  15. }
  16. extension HexColor on String {
  17. Color get color => toColor();
  18. Color toColor() {
  19. String hex = replaceAll('#', '');
  20. if (hex.length == 6) {
  21. hex = 'FF$hex';
  22. }
  23. return Color(int.parse(hex, radix: 16));
  24. }
  25. }
  26. extension LetExtension<T> on T {
  27. /// 类似 Kotlin 的 let 函数,允许对任意对象执行代码块
  28. R let<R>(R Function(T it) block) {
  29. return block(this);
  30. }
  31. }
  32. extension ApplyExtension<T> on T {
  33. /// 类似 Kotlin 的 apply 函数,允许对对象执行配置操作,并返回自身
  34. T apply(void Function(T it) block) {
  35. block(this);
  36. return this;
  37. }
  38. }
  39. extension AlsoExtension<T> on T {
  40. T also(void Function(T it) block) {
  41. block(this);
  42. return this;
  43. }
  44. }
  45. extension RunExtension<T> on T {
  46. R run<R>(R Function(T it) block) => block(this);
  47. }
  48. extension StreamBufferTimeExtension<T> on Stream<T> {
  49. /// 将流中的事件按时间窗口缓冲,每隔 [duration] 时间发送一次缓冲列表
  50. Stream<List<T>> bufferTime(Duration duration) {
  51. StreamController<List<T>>? controller;
  52. List<T> buffer = [];
  53. Timer? timer;
  54. controller = StreamController<List<T>>(
  55. onListen: () {
  56. timer = Timer.periodic(duration, (_) {
  57. if (buffer.isNotEmpty) {
  58. controller?.add(List.from(buffer));
  59. buffer.clear();
  60. }
  61. });
  62. // 监听原始流,收集事件到缓冲区
  63. listen(
  64. (event) => buffer.add(event),
  65. onError: (error) => controller?.addError(error),
  66. onDone: () {
  67. timer?.cancel();
  68. // 流结束时发送剩余缓冲事件
  69. if (buffer.isNotEmpty) {
  70. controller?.add(List.from(buffer));
  71. buffer.clear();
  72. }
  73. controller?.close();
  74. },
  75. );
  76. },
  77. onCancel: () {
  78. timer?.cancel();
  79. buffer.clear();
  80. },
  81. );
  82. // 返回控制器对应的 Stream,而不是控制器本身
  83. return controller.stream;
  84. }
  85. }