2

Im trying to make a list ti json for firestore, and have the following code:

  static Map<String, dynamic> toJson(Message? message) => {
        'id': message?.id,
        'senderId': message?.senderId,
        'receiverId': message?.receiverId,
        'message': message?.message,
        'dateTime': message?.dateTime,
        'timeString': message?.timeString,
        'likes': message?.likes,
        'chatId': message?.chatId,
        'commentCount': message?.commentCount,
        'userIdsWhoLiked': message?.userIdsWhoLiked,
      };

  static Map<String, dynamic> messageListToJson(List<Message?> messages) {
    Map<String, dynamic> messageList = [] as Map<String, dynamic>;
    for (Message? message in messages) {
      messageList.addAll(Message.toJson(message));
    }
    return messageList;
  }

The error is "type 'List' is not a subtype of type 'Map<String, dynamic>' in type cast". For some reason, this is the part throwing the error:

Map<String, dynamic> messageList = [] as Map<String, dynamic>;

Its weird because i have a similar piece of code that works despite being nearly identical. Any idea whats causing this?

1

2 Answers 2

1

You are trying to assign a list to a map

Map<String, dynamic> messageList = [] 

Here [] is an empty list.

You can try this

List<Map<String, dynamic>> messageList = [];

You can try this

Map<String, dynamic> messageList;
Sign up to request clarification or add additional context in comments.

1 Comment

Id like this output to be a single Map of multiple entries if possible, rather than a list of Maps.
1

[] can't be used as Map. Because it is List.

Map<String, dynamic> messageList = [] as Map<String, dynamic>;

Use this {}.

Map<String, dynamic> messageList = {} as Map<String, dynamic>;

I hope it could help.

1 Comment

{} as Map<String, dynamic> is better written as Map<String,dynamic>{}

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.