Actual Behaviour :
I'm working on a podcasts playing application in react-native and implementing track player in it. When i play a podcast in the player screen, tap on next icon twice and then navigate to the topic screen of the podcast being played in the player screen currently, then i'm required to scroll to the podcast item being played from the FlatList in the topic screen and show it as highlighted.
For this i have used scrollToIndex method of FlatList in conjunction with getItemLayout prop of FlatList and passed the index of the current podcast item being played to the method. But the method is not working as expected and is scrolling to wrong position. I have also tried many workarounds with no use.
Expected Behaviour :
I'm supposed to scroll to the particular podcast item being played from the topic screen in the player screen and show it as highlighted. Can someone help me please. Thanks in advance.
What i have tried :
<FlatList
showsVerticalScrollIndicator={false}
style={{ marginLeft: 20, marginRight: 20 }}
ref={(ref) => {
this.flatListRef = ref;
}}
initialScrollIndex={insights.length > 50 ? 50 : 40}
initialNumToRender={2}
getItemLayout={this.getItemLayout}
data={insights}
extraData={this.state}
stickyHeaderIndices={[0]}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
ListHeaderComponent={playAll ? null : this._renderHeader}
ItemSeparatorComponent={ListSeparator}
contentContainerStyle={{...Styles.listBottomSpace}}
legacyImplementation={false}
windowSize={20}
maxToRenderPerBatch = {1}
removeClippedSubviews={false}
onScrollToIndexFailed={(error) => {
this.flatListRef.scrollToOffset({ offset: error.averageItemLength *
error.index, animated: false });
setTimeout(() => {
if (insights.length !== 0 && this.flatListRef !== null) {
this.flatListRef.scrollToIndex({ index: error.index, animated: false
});
}
}, 100);
}}
/>
getItemHeight = (event) => {
if (!this.itemHeight) {
const { height } = event.nativeEvent.layout;
this.itemHeight = height;
}
};
getItemLayout = (data, index) => {
let height = this.itemHeight ? this.itemHeight : 100;
return { length: height, offset: height * index, index };
};
scrollToItem = (insights) => {
const { currentTrack } = this.props;
let activeInsight = currentTrack ? lodash.findIndex(insights, (insight) => {
return (insight.insight_id === Number(currentTrack.id) && insight.insight_title ===
currentTrack.title)
}) : -1;
this.flatListRef &&
activeInsight > -1 &&
this.flatListRef.scrollToIndex({
animated: false,
index: activeInsight,
viewPosition: 0.5,
})
};
Environment :
"react": "16.8.3", "react-native": "0.59.9", "MacOS": "10.15.3"