EgenSolve
EgenSolve

Reputation: 43

How to add a widget to the bottom of a reversed AnimatedList

I have a list of ChatMessageEntity and I use it in my AnimatedList to enable me to add another ChatMessageEntity to it. without rebuilding the whole list. This AnimatedList is reversed to show latest message first. I needed to add the ChatMessageEntity at the bottom. However, when I try to add the ChatMessageEntity, it awlays adds it at the top. I get the length of the list and use a global key of my animated list and use listkey.currentState?.insertItem(messages.length-1);. I don't know if this messages.length-1 is right but when I used messages.length it gave an error that the provided index is not in the range. Can someone show me what is wrong with my code? I even changed the index to any number like 10 and it still added it to the top.

EDIT

List<ChatMessageEntity> messages = [
    // my messages
];

final ScrollController _scrollController = ScrollController();
final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
    
 AnimatedList(
  initialItemCount: messages.length,
  controller: _scrollController,
  key: _listKey,
  reverse: true,
....

My Send Button:

onPressed: () {
  addMessage(ChatMessageEntity(
      id: '${messages.length + 1}',
      message: messageController.text,
      url: null,
      sender: '${UserData.firstName} ${UserData.lastName}',
      type: 'text',
      date: '${DateTime.now().hour} ${DateTime.now().minute}'));
  hasText.value = false;
  messageController.clear();
},
.....
void addMessage(ChatMessageEntity newMessage) {
  messages.add(newMessage);
  print(messages.length);
  listkey.currentState?.insertItem(10);
  scrollController.animateTo(
    0,
    duration: const Duration(milliseconds: 500),
    curve: Curves.easeOut,
  );
}

Upvotes: 0

Views: 86

Answers (0)

Related Questions