I’ve got a ListView widget inside a Consumer widget. What I want to achive is update the element in the ListView when a new element is added or removed.
The code of the Consumer and the ListView is the following:
Consumer(
builder: (context, ref, child) {
final chats = ref.watch(chatsProvider).reversed.toList();
return ListView.builder(
reverse: true,
controller: _scrollController,
itemCount: chats.length,
itemBuilder: (context, index) => ChatItem(
text: chats[index].message,
isMe: chats[index].isMe,
id: chats[index].id
),
);
},
)
When I add new item, it works well, and it gets added to my ListView. When I try to remove an element, the ListView won’t be updated. Here is the code to check it:
class ChatNotifier extends StateNotifier<List<ChatModel>> {
ChatNotifier() : super([]);
void add({required ChatModel chatModel}) {
state = [...state, chatModel];
}
void removeElement({required String id}) {
state.removeWhere((message) => message.id == id);
}
}
final chatsProvider = StateNotifierProvider<ChatNotifier, List<ChatModel>>(
(ref) => ChatNotifier(),
);
What should I add to my code to remove the element from the ListView?
2
Answers
try below code :
Please check below link for your reference:
https://riverpod.dev/docs/providers/state_notifier_provider
Try