-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(hook): refactor useDebounce
- Loading branch information
Showing
2 changed files
with
41 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
## NEXT_VERSION | ||
|
||
### Refactor | ||
|
||
- refactor useDebounce | ||
|
||
## 0.0.2 | ||
|
||
- Add erb widgets | ||
- Add erb theme | ||
|
||
## 1.0.0 | ||
|
||
- init erb_flutter_boilerplate |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,33 @@ | ||
import 'dart:async'; | ||
|
||
import 'package:flutter/foundation.dart'; | ||
import 'package:flutter_hooks/flutter_hooks.dart'; | ||
|
||
import 'use_timeout_fn.dart'; | ||
/// Signature of function that is returned by [useDebounce]. | ||
typedef DebouncedCallback = void Function(VoidCallback callback); | ||
|
||
/// Returns a function whose invocation will be delayed by [duration]. | ||
/// | ||
/// When the returned function is called again, the previous (scheduled) | ||
/// invocation is canceled. | ||
/// | ||
/// See also: | ||
/// | ||
/// * <https://rxmarbles.com/#debounce>, which this hook implements. | ||
DebouncedCallback useDebounce(Duration duration) { | ||
final debouncer = useMemoized(() => _Debouncer(duration), [duration]); | ||
return debouncer.run; | ||
} | ||
|
||
class _Debouncer { | ||
_Debouncer(this.duration); | ||
|
||
final Duration duration; | ||
|
||
// #Example | ||
// useDebounce(() { | ||
// bounceValue.value = inputValue.value; | ||
// }, const Duration(seconds: 1)); | ||
Timer? _timer; | ||
|
||
/// Flutter hook that delays invoking a function until after wait milliseconds | ||
/// have elapsed since the last time the debounced function was invoked. | ||
/// The third argument is the array of values that the debounce depends on, | ||
/// in the same manner as useEffect. The debounce timeout will start when one | ||
/// of the values changes. | ||
void useDebounce(VoidCallback fn, Duration delay, [List<Object?>? keys]) { | ||
final timeout = useTimeoutFn(fn, delay); | ||
useEffect(() => timeout.reset, keys); | ||
void run(VoidCallback callback) { | ||
_timer?.cancel(); | ||
_timer = Timer(duration, callback); | ||
} | ||
} |