Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent inverted Flatlist from scrolling to bottom when new items are added

I am building a chat app, using an inverted Flatlist. I add new items to the top of the list when onEndReached is called and everything works fine.

The problem is that if add items to the bottom, it instantly scrolls to the bottom of the list. That means that the user has to scroll back up to read the messages that were just added (which is terrible).

I tried to call scrollToOffset in onContentSizeChange, but this has a one-second delay where the scroll jumps back and forth.

How can I have the list behave the same way when I add items to the top AND to the bottom, by keeping the same messages on screen instead of showing the new ones?

like image 750
Ryan Pergent Avatar asked May 26 '20 12:05

Ryan Pergent


People also ask

How do you keep the scroll position with FlatList?

In Flatlist set scrollsToTop={false} this will retain position when you navigate back from detail screen.

What strategy would you use to optimize a large list of items on FlatList?

Use getItemLayout​ If all your list item components have the same height (or width, for a horizontal list), providing the getItemLayout prop removes the need for your FlatList to manage async layout calculations. This is a very desirable optimization technique.

What does the key extractor prop of the FlatList do?

It extracts the unique key name and its value and tells the FlatList component to track the items based on that value. The warning will then disappear after this step.

What is the difference between FlatList and SectionList?

SectionList s are like FlatList s, but they can have section headers to separate groups of rows. SectionList s render each item in their input sections using the renderSectionHeader and renderItem prop. Each item in sections should be an object with a unique id (the key), and an array data of row data.


1 Answers

here is demo: https://snack.expo.io/@nomi9995/flatlisttest

Solution 1:

use maintainVisibleContentPosition props for preventing auto scroll in IOS but unfortunately, it's not working on android. but here is PR for android Pull Request. before merge this PR you can patch by own from this PR

<FlatList
  ref={(ref) => { this.chatFlatList = ref; }}
  style={styles.flatList}
  data={this.state.items}
  renderItem={this._renderItem}
  maintainVisibleContentPosition={{
     minIndexForVisible: 0,
  }}
/>

Solution 2:

I found another workaround by keep latest y offset with onScroll and also save content height before and after adding new items with onContentSizeChange and calculate the difference of content height, and set new y offset to the latest y offset + content height difference!

like image 154
Muhammad Numan Avatar answered Sep 28 '22 05:09

Muhammad Numan