0

Looking for an example in dart exactly like this question: How to add element into ArrayList in HashMap

  Map<int, List<Message>> user_id_mapped_to_messages_list = new HashMap();

This throws a null insert, what am I missing here?

  user_id_mapped_to_messages_list[user_id].add(message_to_current_user);

Error:

I/flutter (11992): ==============================================
I/flutter (11992): Message is going to the logged in user id of: 11
I/flutter (11992): Message details:
I/flutter (11992): sender: Instance of 'User'
I/flutter (11992): time: 2020-05-11 22:28:26
I/flutter (11992): text: Message 2 from John to Joe
I/flutter (11992): message added to chat group
E/flutter (11992): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'add' was called on null.
E/flutter (11992): Receiver: null
E/flutter (11992): Tried calling: add(Instance of 'Message')
E/flutter (11992): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (11992): #1      _myappnameMessagesRecentChatsState.getConversations.<anonymous closure>.<anonymous closure> 
(package:myappname_app_androidx/widgets/home/messages/messages_v2/recent_chats.dart:158:83)

No items existed... for loop printing the messages in the array list

user_id_mapped_to_messages_list.forEach((k,v) => print('${k}: ${v}'));
2
  • can you show the error and the code where yoy are declaring and inserting into the lists Commented May 13, 2020 at 16:47
  • Added the error, the code where I'm inserting is too much to post... It's basically just: user_id_mapped_to_messages_list[user_id].add(message); Commented May 13, 2020 at 16:53

1 Answer 1

1

You created user_id_mapped_to_messages_list variable of type Map> but initialised with HashMap because of that you are getting error.

it should be like below.

Map<int, List<Message>> user_id_mapped_to_messages_list = new Map();

Update:

This is happening because when you directly assign or add any value to list when it is not actually initialised, so add following line before a

user_id_mapped_to_messages_list[user_id] = [];

user_id_mapped_to_messages_list[user_id] = [];

    if (user_id_mapped_to_messages_list[user_id] == null) {
      user_id_mapped_to_messages_list[user_id] = [];
      user_id_mapped_to_messages_list[user_id].add(message_to_current_user);
    } else {
      user_id_mapped_to_messages_list[user_id].add(message_to_current_user);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.