Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flat List - ScrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed

setTimeout(() => { this.myFlatList.scrollToIndex({animated:true , index: 100}) }, 100);  

enter image description here

If i use scrolltoindex in flat list return to me this error;

scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed

I tried to use getItemLayout but my flatlist items have different height, how can i fix this?

getItemLayout={(data, index) => (
                {length: 40, offset: 40 * index, index}
              )}
like image 916
Emre Avatar asked Oct 30 '18 07:10

Emre


People also ask

How do I use onScrollToIndexFailed?

onScrollToIndexFailed ​ Used to handle failures when scrolling to an index that has not been measured yet. Recommended action is to either compute your own offset and scrollTo it, or scroll as far as possible and then try again after more items have been rendered.

How do you get the current visible index in nursing flat list?

You can use FlatList onViewableItemsChanged prop to get what you want. viewabilityConfig can help you to make whatever you want with viewability settings. In code example 50 means that item is considered visible if it is visible for more than 50 percents.


1 Answers

I had a similar error with a horizontal list showing images where the selected image should be shown in a carousel when pressed.

I solved it by setting the selected index on the FlatList by using initialScrollIndex. I also used onScrollToIndexFailed to scroll to the correct image for the times when initialScrollIndex failed to show the correct image.

This is done by setting a timeout for 500ms and then scroll to the selected image.

Complete example (with only the props regarding this error):

const flatList = useRef<FlatList>(null);

...

<FlatList
  ref={flatList}
  initialScrollIndex={props.activeIndex}  
  onScrollToIndexFailed={info => {
    const wait = new Promise(resolve => setTimeout(resolve, 500));
    wait.then(() => {
      flatList.current?.scrollToIndex({ index: info.index, animated: true });
    });
  }}
/>
like image 90
Kent Robin Avatar answered Sep 17 '22 11:09

Kent Robin