'Flutter Firestore ) Bad state: field does not exist within the DocumentSnapshotPlatform

I am implementing the project by referring to the sample code before firestore 2.0. I'm going to bring the last document of the Chat collector to StreamBuilder.

Next is my StreamBuilder code.

StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: FirebaseFirestore.instance
          .collection(COL_USERS)
          .doc(_myPerson!.userKey)
          .collection(COL_CHATROOMS)
          .doc(personKey)
          .collection(COL_CHATS)
          .snapshots(includeMetadataChanges: true),
      builder: (BuildContext context,
          AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
        // error check
        if (snapshot.hasError) {
          return SizedBox();
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return SizedBox();
        }

        if (snapshot.data == null) {
          return SizedBox();
        }

        // chat document list
        List<QueryDocumentSnapshot> listChat = snapshot.data!.docs;

        // last chat document // ! error
        QueryDocumentSnapshot lastChat = listChat
            // edit .data()[] => .get()
            .where((element) => element.get(DOC_LASTMSG_TIME) == lastMsgTime)
            .toList()[0];

        NewChatModel lastDataChat =
            NewChatModel.fromJson(lastChat.data() as Map<String, dynamic>);

        return Text("123");
);

However, the following error is printed from the code below:

QueryDocumentSnapshot lastChat = listChat
    .where((element) => element.get(DOC_LASTMSG_TIME) == lastMsgTime)
    .toList()[0];

NewChatModel lastDataChat =
    NewChatModel.fromJson(lastChat.data() as Map<String, dynamic>);

Error

════════ Exception caught by widgets library ═══════════════════════════════════
The following StateError was thrown building StreamBuilder<QuerySnapshot<Object?>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Object?>, AsyncSnapshot<QuerySnapshot<Object?>>>#cc2a2):
Bad state: field does not exist within the DocumentSnapshotPlatform
The relevant error-causing widget was
StreamBuilder<QuerySnapshot<Object?>>
When the exception was thrown, this was the stack

Can I know how to solve this problem?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source