Flutter 使用自定义卷轴的动态边界颤振页面视图
我正在尝试动态设置页面视图边界。 这里有一个简化的示例,从第10页开始,左右边界由随机数生成器(leftEnd,rightEnd)设置Flutter 使用自定义卷轴的动态边界颤振页面视图,flutter,Flutter,我正在尝试动态设置页面视图边界。 这里有一个简化的示例,从第10页开始,左右边界由随机数生成器(leftEnd,rightEnd)设置 导入“包装:颤振/材料.省道”; 导入“dart:math”; void main()=>runApp(新的MyApp()); 类MyApp扩展了无状态小部件{ @凌驾 小部件构建(构建上下文){ 返回新材料PP( 标题:“颤振演示”, 主页:新建MyTabbedPage(), ); } } 类MyTabbedPage扩展StatefulWidget{ cons
导入“包装:颤振/材料.省道”;
导入“dart:math”;
void main()=>runApp(新的MyApp());
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回新材料PP(
标题:“颤振演示”,
主页:新建MyTabbedPage(),
);
}
}
类MyTabbedPage扩展StatefulWidget{
constmytabbedpage({Key}):super(Key:Key);
@凌驾
_MyTabbedPageState createState()=>new_MyTabbedPageState();
}
类_MyTabbedPageState使用SingleTickerProviderStateMixin扩展状态{
最后的leftEnd=Random().nextInt(5);
最终右端=10+随机().nextInt(5);
CustomScrollPhysics scrollPhysics=CustomScrollPhysics();
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(),
正文:PageView.builder(
控制器:页控制器(初始页:10),
物理学:物理学,
itemBuilder:(上下文,索引){
scrollPhysics.leftEnd=(索引=右端);
//------打印(1)----------
打印(“是左端:${index=rightEnd}”);
打印(“scrollphysics.leftEnd:${scrollphysics.leftEnd}”);
打印(“scrollphysics.rightEnd:${scrollphysics.rightEnd}”);
返回中心(
子项:文本(“项$index”),
);
}
));
}
}
类CustomScrollPhysics扩展了ScrollPhysics{
CustomScrollPhysics({ScrollPhysics parent}):超级(父:父);
bool leftEnd=false;
bool rightEnd=false;
bool isGoingLeft=false;
@凌驾
CustomScrollPhysics应用程序(ScrollPhysics祖先){
返回自定义物理(父级:buildParent(祖先));
}
@凌驾
双ApplyPhysistoUserOffset(ScrollMetrics位置,双偏移){
isGoingLeft=偏移量。符号<0;
返回偏移量;
}
@凌驾
双applyBoundaryConditions(ScrollMetrics位置,双值){
//打印(“应用边界条件”);
断言(){
if(值==位置像素){
投掷抖动误差(
“$runtimeType.applyBoundaryConditions()被冗余调用。\n”
'建议的新位置,$value,正好等于
'给定${position.runtimeType},${position.pixels}。\n'
'仅当值为“”时才应调用applyBoundaryConditions方法'
'将实际更改像素,否则是多余的。\n'
'所讨论的物理对象是:\n'
“$this\n”
'所讨论的位置对象是:\n'
“$position\n”);
}
返回true;
}());
如果您的CustomScrollPhysics
所扩展的(valueScrollPhysics
被标记为不可变。即使您在itemBuilder
中更改其布尔值,实际的布尔值也不会更改(如不在applyBoundaryConditions
中打印leftEnd
和rightEnd
所示)。我没有官方解释为什么scrollPhysics。在itemBuilder
中,leftEnd
显示了所需的已更改布尔值,而它在其类中本身没有更改,但我猜这是因为您没有将这些变量设置为应设置的final
,并且没有任何东西阻止您更改它们以使\u MyTabbedPageState
中的localscrollPhysics
显示这些更改,即使这些更改没有在内部更改。isGoingLeft
之所以打印,是因为它是在CustomScrollPhysics
本身内部更改的,而不是从外部更改的,如itemBuilder
中所示
作为快速修复,我创建了另一个类:
class Status {
bool leftEnd = false;
bool rightEnd = false;
bool isGoingLeft = false;
}
稍微更改了您的CustomScrollPhysics
:
class CustomScrollPhysics extends ScrollPhysics {
final Status status;
CustomScrollPhysics(this.status, {ScrollPhysics parent})
: super(parent: parent);
@override
CustomScrollPhysics applyTo(ScrollPhysics ancestor) {
return CustomScrollPhysics(this.status, parent: buildParent(ancestor));
}
...
并在您所在州的构造函数调用中添加了一个Status
实例:
CustomScrollPhysics scrollPhysics = CustomScrollPhysics(Status());
将每个更改应用于此。状态内部自定义滚动物理。现在它应该可以按预期工作
CustomScrollPhysics scrollPhysics = CustomScrollPhysics(Status());