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
You are trying to assign a list to a map
Here [] is an empty list.
You can try this
You can try this
[] can’t be used as Map. Because it is List.
Use this {}.
I hope it could help.