Align a flutter PageView to the screen left. After making a deeper analysis on my own needs and checking the source code for the PageView widget, I realized that that I needed a scrolling widget that works in a item by item basis, but at the same time I needed that the space given to every item was the same as a normal scroll, so I needed to change the ScrollPhysics of a normal scroller. In found this post which describes scroll physics in flutter at some extent and was close to my needs, the difference was I needed to add space at bith sides of the current visible widget, not only to the right.
So I took the CustomScrollPhysics in the post and modified it in this way (the changed parts from the post code are sourrounded withh <-- and --> comments:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
class CustomScrollPhysics extends ScrollPhysics { final double itemDimension; CustomScrollPhysics({this.itemDimension, ScrollPhysics parent}) : super(parent: parent); @override CustomScrollPhysics applyTo(ScrollPhysics ancestor) { return CustomScrollPhysics( itemDimension: itemDimension, parent: buildParent(ancestor)); } double _getPage(ScrollMetrics position, double portion) { // <-- return (position.pixels + portion) / itemDimension; // --> } double _getPixels(double page, double portion) { // <-- return (page * itemDimension) - portion; // --> } double _getTargetPixels( ScrollPosition position, Tolerance tolerance, double velocity, double portion, ) { // <-- double page = _getPage(position, portion); // --> if (velocity < -tolerance.velocity) { page -= 0.5; } else if (velocity > tolerance.velocity) { page += 0.5; } // <-- return _getPixels(page.roundToDouble(), portion); // --> } @override Simulation createBallisticSimulation( ScrollMetrics position, double velocity) { // If we're out of range and not headed back in range, defer to the parent // ballistics, which should put us back in range at a page boundary. if ((velocity <= 0.0 && position.pixels <= position.minScrollExtent) || (velocity >= 0.0 && position.pixels >= position.maxScrollExtent)) return super.createBallisticSimulation(position, velocity); final Tolerance tolerance = this.tolerance; // <-- final portion = (position.extentInside - itemDimension) / 2; final double target = _getTargetPixels(position, tolerance, velocity, portion); // --> if (target != position.pixels) return ScrollSpringSimulation(spring, position.pixels, target, velocity, tolerance: tolerance); return null; } @override bool get allowImplicitScrolling => false; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.