Skip to content

FlatList scrollToIndex scrolls to wrong place when used for the first time #19441

@amcvitty

Description

@amcvitty

When using a FlatList to display a small number of Buttons, the first time I call scrollToIndex, it miscalculates the position to put things on screen relative to the viewPosition specified.

Environment

Environment:
OS: macOS High Sierra 10.13.4
Node: 9.8.0
Yarn: 1.5.1
npm: 5.6.0
Watchman: 4.9.0
Xcode: Xcode 9.3.1 Build version 9E501
Android Studio: Not Found

Packages: (wanted => installed)
react: 16.3.1
react-native: 0.55.2

Steps to Reproduce

Load this snack: https://snack.expo.io/@amcvitty/flatlist-scroll-bug

This app simply scrolls the appropriate red box in the FlatList at the top to the center of the view when you click the corresponding button in the list below.

  • Click the "D2" button. Note that the D2 box scrolls to the extreme left ignoring the viewPosition specified (this is incorrect)
  • Click the "D2" button again. Note that the D2 box now scrolls to the center, respecting the viewposition
  • Further clicks on D2 will continue to leave the box in the middle correctly.

Expected Behavior

The first click should take the D2 box to the center

Actual Behavior

The first click ignores the viewPosition, unless the user does an actual scroll before the first call to scrollToIndex.

My debugging

I did a bit of debugging and the reason seems to be that this._scrollMetrics.visibleLength in VirtualizedList has been incorrectly set to 0 in a call to onScroll that happens after onLayout (when it is set correctly), but before any user interaction. The list receives a scroll event with all zeros, and specifically on this line:

VirtualizedList.js:1267: let visibleLength = this._selectLength(e.nativeEvent.layoutMeasurement);

the layoutMeasurement is 0.

Since the visibleLength is used in onScrollToIndex to calculate the appropriate scroll offset, the calculation is incorrect.

Scroll events triggered by user action have real event content and so the layoutMeasurement is reset correctly (to 375 on my iphone 7).

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugComponent: FlatListStaleThere has been a lack of activity on this issue and it may be closed soon.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions