| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import 'dart:async';
- import 'dart:ui';
- extension TrimAllExtension on String {
- String trimAll() {
- return replaceAll(RegExp(r'\s+'), '');
- }
- String trimAndReduceSpaces() {
- return trim().replaceAll(RegExp(r'\s+'), ' ');
- }
- }
- extension FutureMap<T> on Future<T> {
- Future<R> map<R>(R Function(T) transform) {
- return then(transform);
- }
- }
- extension HexColor on String {
- Color get color => toColor();
- Color toColor() {
- String hex = replaceAll('#', '');
- if (hex.length == 6) {
- hex = 'FF$hex';
- }
- return Color(int.parse(hex, radix: 16));
- }
- }
- extension LetExtension<T> on T {
- /// 类似 Kotlin 的 let 函数,允许对任意对象执行代码块
- R let<R>(R Function(T it) block) {
- return block(this);
- }
- }
- extension ApplyExtension<T> on T {
- /// 类似 Kotlin 的 apply 函数,允许对对象执行配置操作,并返回自身
- T apply(void Function(T it) block) {
- block(this);
- return this;
- }
- }
- extension AlsoExtension<T> on T {
- T also(void Function(T it) block) {
- block(this);
- return this;
- }
- }
- extension RunExtension<T> on T {
- R run<R>(R Function(T it) block) => block(this);
- }
- extension StreamBufferTimeExtension<T> on Stream<T> {
- /// 将流中的事件按时间窗口缓冲,每隔 [duration] 时间发送一次缓冲列表
- Stream<List<T>> bufferTime(Duration duration) {
- StreamController<List<T>>? controller;
- List<T> buffer = [];
- Timer? timer;
- controller = StreamController<List<T>>(
- onListen: () {
- timer = Timer.periodic(duration, (_) {
- if (buffer.isNotEmpty) {
- controller?.add(List.from(buffer));
- buffer.clear();
- }
- });
- // 监听原始流,收集事件到缓冲区
- listen(
- (event) => buffer.add(event),
- onError: (error) => controller?.addError(error),
- onDone: () {
- timer?.cancel();
- // 流结束时发送剩余缓冲事件
- if (buffer.isNotEmpty) {
- controller?.add(List.from(buffer));
- buffer.clear();
- }
- controller?.close();
- },
- );
- },
- onCancel: () {
- timer?.cancel();
- buffer.clear();
- },
- );
- // 返回控制器对应的 Stream,而不是控制器本身
- return controller.stream;
- }
- }
|