runable
This commit is contained in:
102
lib/core/utils/debouncer.dart
Normal file
102
lib/core/utils/debouncer.dart
Normal file
@@ -0,0 +1,102 @@
|
||||
/// Performance utility for debouncing rapid function calls
|
||||
///
|
||||
/// Use cases:
|
||||
/// - Search input (300ms delay before search)
|
||||
/// - Auto-save functionality
|
||||
/// - API request rate limiting
|
||||
/// - Scroll position updates
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// Debouncer utility to prevent excessive function calls
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final searchDebouncer = Debouncer(milliseconds: 300);
|
||||
///
|
||||
/// void onSearchChanged(String query) {
|
||||
/// searchDebouncer.run(() {
|
||||
/// performSearch(query);
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
class Debouncer {
|
||||
final int milliseconds;
|
||||
Timer? _timer;
|
||||
|
||||
Debouncer({required this.milliseconds});
|
||||
|
||||
/// Run the action after the debounce delay
|
||||
void run(VoidCallback action) {
|
||||
_timer?.cancel();
|
||||
_timer = Timer(Duration(milliseconds: milliseconds), action);
|
||||
}
|
||||
|
||||
/// Cancel any pending debounced action
|
||||
void cancel() {
|
||||
_timer?.cancel();
|
||||
}
|
||||
|
||||
/// Dispose of the debouncer
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// Throttler utility to limit function call frequency
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final scrollThrottler = Throttler(milliseconds: 100);
|
||||
///
|
||||
/// void onScroll() {
|
||||
/// scrollThrottler.run(() {
|
||||
/// updateScrollPosition();
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
class Throttler {
|
||||
final int milliseconds;
|
||||
Timer? _timer;
|
||||
bool _isReady = true;
|
||||
|
||||
Throttler({required this.milliseconds});
|
||||
|
||||
/// Run the action only if throttle period has passed
|
||||
void run(VoidCallback action) {
|
||||
if (_isReady) {
|
||||
_isReady = false;
|
||||
action();
|
||||
_timer = Timer(Duration(milliseconds: milliseconds), () {
|
||||
_isReady = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel throttler
|
||||
void cancel() {
|
||||
_timer?.cancel();
|
||||
_isReady = true;
|
||||
}
|
||||
|
||||
/// Dispose of the throttler
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// Search-specific debouncer with common configuration
|
||||
class SearchDebouncer extends Debouncer {
|
||||
SearchDebouncer() : super(milliseconds: 300);
|
||||
}
|
||||
|
||||
/// Auto-save debouncer with longer delay
|
||||
class AutoSaveDebouncer extends Debouncer {
|
||||
AutoSaveDebouncer() : super(milliseconds: 1000);
|
||||
}
|
||||
|
||||
/// Scroll throttler for performance
|
||||
class ScrollThrottler extends Throttler {
|
||||
ScrollThrottler() : super(milliseconds: 100);
|
||||
}
|
||||
Reference in New Issue
Block a user