Search code examples
flutterstream-builder

How to get values inside _JsonDocumentSnapshot?


Flutter Streambuilder code below runs without error and returns (screenshot at bottom):

ID: AzFdOO9WsFaFbTxTQsuo
Data: Instance of '_JsonDocumentSnapshot'

How do I get to the values inside the _JsonDocumentSnapshot and display them in the Text() widget?

For instance, there's a string field called "name", but I can't figure out how to get to it.

StreamBuilder(
    stream: FirebaseFirestore.instance
                .collection("groceries")
                .doc(widget.docId)
                .snapshots(),
        builder: (context, streamSnapshot) {
            if (streamSnapshot.connectionState == ConnectionState.waiting) {
                return const Text("Loading");
            } else if (streamSnapshot.hasData) {
                return Text("ID: ${widget.docId}\n"
                            "Data: ${streamSnapshot.data}");
            } else {
                return const Text("No Data");
            }
        }
    )

Screenshot of _JsonDocumentSnapshot

Thanks for your help!


Solution

  • the following Stream, return an object with a type of DocumentSnapshot :

    FirebaseFirestore.instance.collection("groceries").doc(widget.docId).snapshots();
    

    and that type contains the document snapshot, and also contains more additional information about the document.

    so in order to get the JSON Map<String, dynamic> which represents the data of the Firestore document, you need to call data() on the result of the snapshot.data(), so you need to try the following:

    StreamBuilder<DocumentSnapshot>(
    stream: FirebaseFirestore.instance
                .collection("groceries")
                .doc(widget.docId)
                .snapshots(),
        builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> streamSnapshot) {
            if (streamSnapshot.connectionState == ConnectionState.waiting) {
                return const Text("Loading");
            } else if (streamSnapshot.hasData) {
                return Text("ID: ${widget.docId}\n"
                            "Data: ${streamSnapshot.data.data()}"); // added data()
            } else {
                return const Text("No Data");
            }
        }
    )
    

    now it should show the Map<String, dynamic> object which contains your document data in the Text widget.

    hope this helps.