I am implementing a discussion screen that contain a list of messages so I used A listview. the list of ListView ih handled with bloc so when a message is added the bloc emit new list that contain the old messages and the new message. here is my ListView widget
BlocBuilder<DiscussionBloc,
DiscussionState>(
buildWhen: (previous, current) =>
previous.messages != current.messages,
builder: (context, newState) {
return ListView.builder(
padding: EdgeInsets.only(bottom: 10.h),
shrinkWrap: true,
reverse: true,
itemCount: newState.hasReachedMax
? newState.messages.length
: newState.messages.length + 1,
itemBuilder: (builder, index) =>
_buildMessageBubble(
context,
index,
widget.state.messages,
widget.state.conversation,
widget.state.message,
widget.state.isMessageLoading),
);
},
),
when a message is added I emit the state like this
emit(state.copyWith(messages: [event.message, ...state.messages ]));
i found that when I add the new message to the head of list the old messages index changed so the list view rebuild their child and when I emit this list
[...state.messages, event.message]
the problem don't occurs.
In my case I have to add the message in head of list.
is therea solution to prevent the listView from being reinitialized there widgets every time the list of messages changed ?
You need to overload the == operator on Messages class.
You can use this package for ease. Equatable