Last active
February 19, 2019 13:26
-
-
Save JulianBissekkou/7d3a270bd3e6ece2fca1430cac55e977 to your computer and use it in GitHub Desktop.
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 ScrollToIndexConverter extends StatefulWidget { | |
final Widget child; | |
final int itemCount; | |
final double dragExtentPercentage; | |
ScrollToIndexConverter({ | |
@required this.child, | |
@required this.itemCount, | |
this.dragExtentPercentage = 0.2, | |
}); | |
@override | |
_ScrollToIndexConverterState createState() => _ScrollToIndexConverterState(); | |
} | |
class _ScrollToIndexConverterState extends State<ScrollToIndexConverter> { | |
double _dragOffset = 0; | |
IndexCalculator indexCalculator; | |
@override | |
void initState() { | |
indexCalculator = IndexCalculator(count: widget.itemCount); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return NotificationListener<ScrollNotification>( | |
onNotification: _handleScrollNotification, | |
child: NotificationListener<OverscrollIndicatorNotification>( | |
onNotification: _handleGlowNotification, | |
child: widget.child, | |
), | |
); | |
} | |
// ----- | |
// Handle notifications | |
// ----- | |
bool _handleScrollNotification(ScrollNotification notification) { | |
var progress = _calculateScrollProgress(notification); | |
var index = indexCalculator.getIndexForScrollPercent(progress); | |
return false; | |
} | |
double _calculateScrollProgress(ScrollNotification notification) { | |
var containerExtent = notification.metrics.viewportDimension; | |
if (notification is ScrollUpdateNotification) { | |
_dragOffset -= notification.scrollDelta; | |
} | |
if (notification is OverscrollNotification) { | |
_dragOffset -= notification.overscroll; | |
} | |
var percent = _dragOffset / (containerExtent * widget.dragExtentPercentage); | |
return percent.clamp(0.0, 1.0); | |
} | |
bool _handleGlowNotification(OverscrollIndicatorNotification notification) { | |
if (notification.depth != 0 || !notification.leading) return false; | |
notification.disallowGlow(); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment