我和ScrollablePositionedList一起工作了一段时间。根据我发现的文档,它说ScrollablePositionedList对ListView的工作方式略有相同。我的问题是,我想将ScrollablePositionedList的初始索引设置在屏幕高度的70%左右的位置,并且我打算通过设置该初始索引的像素来实现。但是,我很难找到如何为ScrollablePositionedList和ItemScrollController设置初始滚动偏移量。请帮帮我
发布于 2022-05-14 16:57:13
您可以在使用和initialAlignment属性构建小部件时设置初始索引。这种对齐方式使用起来有点复杂,所以我为您编写了一个小函数。
int initialIndex = 1;
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
return ScrollablePositionedList.builder(
initialScrollIndex: initialIndex,
initialAlignment: getAlignment(
index: initialIndex,
itemHeight: list[initialIndex].height,
viewPortHeight: constraints.maxHeight,
alignmentOnItem: 0.5, //middle of item
),这是对齐的计算。您可以配置使用alignmentOnItem显示项目的位置。
double getAlignment({
required int index,
required double viewPortHeight,
///The item height at the [index]. If all your items have the same height this
///can be a static value
required double itemHeight,
///A double value between |0, 1| is expected, where percentage of the item
///should be positioned based on the center of the screen.
///(0 is top of the item, 1 is bottom if the item)
double alignmentOnItem = 0.5,
}) {
assert(alignmentOnItem >= 0 && alignmentOnItem <= 1,
"Alignment on item is expected to be within 0 and 1");
final relativePageHeight = 1 / viewPortHeight * itemHeight;
return 0.5 - relativePageHeight * alignmentOnItem;
}请注意,如果您将alignmentOnItem设置为无法到达的位置(这样就会发生过度滚动),那么显然无法达到所需的位置。请参见索引0处的对齐。
https://stackoverflow.com/questions/68621668
复制相似问题