Created
September 4, 2024 06:37
-
-
Save bambinoua/1e8d9873e08e4d09535d8f5830fa5152 to your computer and use it in GitHub Desktop.
ScrollableDebouce
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
class ScrollableDebounce extends StatefulWidget { | |
const ScrollableDebounce({ | |
Key? key, | |
required this.controller, | |
required this.onScroll, | |
this.debounceTime = const Duration(milliseconds: 200), | |
required this.child, | |
}) : super(key: key); | |
/// An object that can be used to control the position to which this scroll | |
/// view is scrolled. | |
final ScrollController controller; | |
/// The time for debouncing scroll events. | |
/// | |
/// Default value is `Duration(milliseconds: 200)`. | |
final Duration debounceTime; | |
/// Callback on debounced scroll event. | |
final void Function(ScrollPosition scrollPosition) onScroll; | |
/// The widget below this widget in the tree. | |
/// | |
/// {@template flutter.widgets.ProxyWidget.child} | |
/// This widget can only have one child. To lay out multiple children, let this | |
/// widget's child be a widget such as [Row], [Column], or [Stack], which have a | |
/// `children` property, and then provide the children to that widget. | |
/// {@endtemplate} | |
final Widget child; | |
@override | |
State<ScrollableDebounce> createState() => _ScrollableDebounceState(); | |
} | |
class _ScrollableDebounceState extends State<ScrollableDebounce> { | |
final _streamController = StreamController<ScrollPosition>.broadcast(); | |
late final StreamSubscription<ScrollPosition> _streamSubscription; | |
@override | |
void dispose() { | |
widget.controller.removeListener(_onScroll); | |
_streamSubscription.cancel(); | |
_streamController.close(); | |
super.dispose(); | |
} | |
@override | |
void initState() { | |
super.initState(); | |
_streamSubscription = _streamController.stream | |
.debounceTime(widget.debounceTime) | |
.listen(widget.onScroll); | |
widget.controller.addListener(_onScroll); | |
} | |
@override | |
void didUpdateWidget(covariant ScrollableDebounce oldWidget) { | |
super.didUpdateWidget(oldWidget); | |
if (widget.controller != oldWidget.controller) { | |
widget.controller.addListener(_onScroll); | |
oldWidget.controller.removeListener(_onScroll); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return widget.child; | |
} | |
void _onScroll() { | |
if (widget.controller.hasClients) { | |
_streamController.add(widget.controller.position); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment