Skip to content

Instantly share code, notes, and snippets.

@MacDeveloper1
Created September 6, 2023 09:24
Show Gist options
  • Save MacDeveloper1/b265c0a6e3b0b7ab4f99422f9a2a300c to your computer and use it in GitHub Desktop.
Save MacDeveloper1/b265c0a6e3b0b7ab4f99422f9a2a300c to your computer and use it in GitHub Desktop.
ScrollableDebouce
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