Skip to content

Instantly share code, notes, and snippets.

@Kavantix
Last active May 7, 2020 15:12
Show Gist options
  • Save Kavantix/3a0bad901d919e51618be2383056643b to your computer and use it in GitHub Desktop.
Save Kavantix/3a0bad901d919e51618be2383056643b to your computer and use it in GitHub Desktop.
Flutter Scroll Physics that always ends on a whole page
class PageAlignedScrollPhysics extends ScrollPhysics {
final double pageSize;
PageAlignedScrollPhysics({@required this.pageSize, ScrollPhysics parent}) : super(parent: parent);
@override
PageAlignedScrollPhysics applyTo(ScrollPhysics ancestor) {
return PageAlignedScrollPhysics(pageSize: pageSize, parent: buildParent(ancestor));
}
@override
Simulation createBallisticSimulation(ScrollMetrics position, double velocity) {
if (position.outOfRange) return super.createBallisticSimulation(position, velocity);
final frictionSimulation = FrictionSimulation(0.135, position.pixels, velocity * 0.91);
double endPosition = frictionSimulation.finalX;
if (endPosition <= position.minScrollExtent || endPosition >= position.maxScrollExtent)
return super.createBallisticSimulation(position, velocity);
final page = (endPosition / pageSize).roundToDouble().clamp(0.0, double.maxFinite);
endPosition = page * pageSize;
if ((endPosition - position.pixels).abs() < tolerance.distance) return null;
if (velocity.abs() < tolerance.velocity) {
return ScrollSpringSimulation(
spring,
position.pixels,
endPosition,
velocity,
tolerance: tolerance,
);
}
velocity = velocity.abs().clamp(200.0, double.maxFinite) * velocity.sign;
return FrictionSimulation.through(
position.pixels,
endPosition,
velocity,
tolerance.velocity * velocity.sign,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment