skip to Main Content

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


  1. try below code :

    void removeElement({required String id}) {
    state = [
          for (final chatModel in state)
            if (chatModel.id != id) chatModel,
        ];
    }
    

    Please check below link for your reference:
    https://riverpod.dev/docs/providers/state_notifier_provider

    Login or Signup to reply.
  2. Try

    state = [...state].removeWhere((message) => message.id == id);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search