Home > OS >  How to get values inside _JsonDocumentSnapshot?
How to get values inside _JsonDocumentSnapshot?

Time:11-24

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!

CodePudding user response:

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.

CodePudding user response:

In your code example streamSnapshot.data is an Object or a dynamic type variable.

To access the json value of your data, you have to specify the key corresponding to your value.

streamSnapshot.data['banana']

  • Related