I'm working with ScrollablePositionedList in flutter for a while. From the document I found, it said ScrollablePositionedList works slightly the same with ListView. My problem is that I want to set the initial index of the ScrollablePositionedList in the position around 70% of screen height from the top of the screen, and I intend to do with by setting the pixel for that initial index. However, I'm struggling to find how to set initial scroll offset for the ScrollablePositionedList with ItemScrollController. Please help me


Solution 1: Paul

You can set the initial index when building the widget with initialScrollIndex and initialAlignment property. The alignment is a bit more complicated to use so I wrote a little function for you.

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
           ),

And here is the calculation for the alignment. You can configure in what position the item should be shown with 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;
  }

Note that if you set the alignmentOnItem to something that cannot be reached (so that an overscroll happens) the desired position obviously cannot be reached. See alignment at index 0.