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?
In Flatlist set scrollsToTop={false} this will retain position when you navigate back from detail screen.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With