【发布时间】:2019-10-07 12:17:06
【问题描述】:
我想使用自定义ScrollPhysics 创建进度PageView,因此用户只能滚动到已完成的选项卡。请参阅下图以供参考,右上角是进度(绿色 = 可访问,红色 = 不可访问页面):
在屏幕截图中,我完成了第 1 页和第 2 页,我不想让用户滑动到现在正在发生的第 3 页。我阅读了scroll_physics.dart 中有关 iOS 和 Android 实现的示例。但我还是卡住了。
我试过这个here,但它被窃听了。您可以阻止用户继续前进,但如果最后一个可访问的页面不完全可见,就像在屏幕截图中一样 滚动已被阻止,您无法再向右滚动。
这是我现在的代码:
调用自:
PageView(
controller: PageController(
initialPage: model.initallPage,
),
children: pages,
physics: model.currentPage >= model.lastAccessiblePage ? CustomScrollPhysics(CustomScrollStatus()..rightEnd = true) : ScrollPhysics(),
onPageChanged: (value) {
model.currentPage = value;
},
),
自定义 ScrollPhysics:
class CustomScrollStatus {
bool leftEnd = false;
bool rightEnd = false;
bool isGoingLeft = false;
bool isGoingRight = false;
}
class CustomScrollPhysics extends ScrollPhysics {
final CustomScrollStatus status;
CustomScrollPhysics(
this.status, {
ScrollPhysics parent,
}) : super(parent: parent);
@override
CustomScrollPhysics applyTo(ScrollPhysics ancestor) {
return CustomScrollPhysics(this.status, parent: buildParent(ancestor));
}
@override
double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
status.isGoingLeft = offset.sign < 0;
return offset;
}
@override
double applyBoundaryConditions(ScrollMetrics position, double value) {
if (value < position.pixels && position.pixels <= position.minScrollExtent) {
print('underscroll');
return value - position.pixels;
}
if (position.maxScrollExtent <= position.pixels && position.pixels < value) {
print('overscroll');
return value - position.pixels;
}
if (value < position.minScrollExtent && position.minScrollExtent < position.pixels) {
print('hit top edge');
return value - position.minScrollExtent;
}
if (position.pixels < position.maxScrollExtent && position.maxScrollExtent < value) {
print('hit bottom edge');
return value - position.maxScrollExtent;
}
if (status.leftEnd) print("leftEnd");
if (status.rightEnd) print("rightEnd");
if (status.isGoingLeft) print("isGoingLeft");
if (status.isGoingRight) print("isGoingRight");
// do something to block movement > accesssible page
print('default');
return 0.0;
}
}
编辑:
我想到了一个完全不同的解决方案。动态更改 PageView 的子项。我仍然对覆盖“ScrollPhysics”解决方案感兴趣,因为我认为它更干净。
children: pages
【问题讨论】:
-
这里描述了一个更好的解决方案:stackoverflow.com/a/63823639/4779937
标签: flutter overriding