'Flutter FirebaseAnimatedList Chat - Scroll to new messages
I am making a simple chat with Firebase and Flutter. I am using FirebaseAnimatedList but I have a problem. By default, the list is ordered from oldest message on top to the newest on bottom. This is the correct order, but when new messages arrives, the list does not scroll to the bottom automatically. What I wanted to do is to reverse the list but then reorder the items the correct way. This way the list should automatically gravitate towards the bottom then items are added. This does not work though as I get an error "assert(index != null && index >= 0)" even if my code (see below) should never return something < 0.
reverse: true,
sort: (DataSnapshot a, DataSnapshot b) {
if ( a.value != null && b.value != null ) {
DateTime ats = DateTime.parse((a.value as Map<dynamic, dynamic>)['timestamp']).toLocal();
DateTime bts = DateTime.parse((b.value as Map<dynamic, dynamic>)['timestamp']).toLocal();
return ats.isBefore(bts) ? 1 : 0;
}
return 0;
},
What am I doing wrong and what should I do to make the chat work as I want?
Best regards
Solution 1:[1]
Add this under your widget build context
WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mohammad Abd-elmoniem |