我想循环从Firebase实时数据库接收到的数据,对于每个数据,通过我的ChatData模型传递它。然而,当我试图传入snapshot.value时,它说The argument type 'Object?' can't be assigned to the parameter type 'Map<dynamic, dynamic>?'.如何修改snapshot.value以便我可以这样做?
代码:
event.snapshot.children.forEach((snapshot) {
_dataList.add(snapshot.value);
msg = ChatData.fromJson(snapshot.value);
});ChatData模型:
ChatData.fromJson(Map<dynamic, dynamic>? json): //Transform JSON into Message
uid = json?['uid'] as String,
text = json?['text'] as String,
timestamp = DateTime.parse(json?['timestamp'] as String),
type = json?['type'] as String,
filterID = json?['filterID'] as String,
mumbleURL = json?['mumbleURL'] as String;我不明白的是,在这段代码的另一个版本中,我只是将快照中的每一段数据添加到一个List中,然后按索引迭代这个列表索引,它工作得很好。首先,放入一个List允许我将每个元素传递到ChatData.fromJSON中.
event.snapshot.children.forEach((snapshot) {
_dataList.add(snapshot.value);
});
_dataList.forEach((element) {
msg = ChatData.fromJson(element); //This works just fine...why?
});发布于 2022-06-06 05:20:51
这样修改您的ChatData模型。
ChatData.fromDocumentSnapshot(DocumentSnapshot jsonMap) {
try {
uid = jsonMap.get('uid') != null ? jsonMap.get('uid').toString() : '';
text = jsonMap.get('text') != null ? jsonMap.get('text').toString() : '';
timestamp = DateTime.parse(jsonMap.get('timestamp').toString());
type = jsonMap.get('type') != null ? jsonMap.get('type').toString() : '';
filterID = jsonMap.get('filterID') != null ? jsonMap.get('filterID').toString() : '';
mumbleURL = jsonMap.get('mumbleURL') != null ? jsonMap.get('mumbleURL').toString() : '';
} catch (e) {
uid = '';
text = '';;
type = '';
print(e);
}
}getChats就像这样。
Stream<List<ChatData>> getChats(Message message) {
return FirebaseFirestore.instance.collection("messages").doc(message.id).collection("chats").orderBy('time', descending: true).snapshots().map((QuerySnapshot query) {
List<ChatData> retVal = [];
query.docs.forEach((element) {
retVal.add(Chat.fromDocumentSnapshot(element));
});
return retVal;
});
}希望你能从中得到一个想法。
https://stackoverflow.com/questions/72513109
复制相似问题