简体   繁体   中英

Check if a field exists in a document snapshot firestore

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());
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM