Home > Back-end >  Flutter: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic&
Flutter: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic&

Time:07-23

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?

CodePudding user response:

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;

CodePudding user response:

[] 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.

  • Related