skip to Main Content

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?

2

Answers


  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;
    
    Login or Signup to reply.
  2. [] 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search