I have a MessageModel in which there are a few fields. But the field "edited" does not exist in the document of each message. It is a new field that I want to add later in the future. When I get all messages using stream it throws the error.
Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform
Is there any way I can check if the field "edited" exists in the model or ignore it?
This is my MessageModel:
factory MessageModel.fromJson(DocumentSnapshot snapshot) => MessageModel(
chatId: snapshot["chat_id"],
messageId: snapshot["message_id"],
userId: snapshot["user_id"],
you: snapshot["you"],
time: snapshot["time"],
seen: snapshot["seen"],
type: snapshot["type"],
message: snapshot["message"],
fileURL: snapshot["file_url"] ?? "" ,
thumbnail: snapshot["thumbnail"] ?? "" ,
isUploading: RxBool(false),
isPlaying: RxBool(false),
file: File("").obs,
thumb: Uint8List(5).obs,
edited: snapshot["edited"]
);
I am using this stream to get all my messages from firestore. Or can I check here if the field exists?
Flutter code:
Stream<List<MessageModel>> getMessages() {
Stream<QuerySnapshot> stream =
CollectionReferences.chatRef.doc(userID.value).collection("messages").orderBy("time", descending: true).snapshots();
return stream.map((data) => data.docs.map((e) => MessageModel.fromJson(e)).toList());
}
CodePudding user response:
If you capture the data as a map, you can check if the map contains a key:
edited: (snapshot.data() as Map<String, dynamic>).containsKey("edited") ?
snapshot["edited"] : null