Kushagra
Kushagra

Reputation: 113

How do I display text from firestore data in flutter?

I am new to firebase/firestore and wanted to add firestore to my app. My app currently has a login and adds data to the database with the UID set as the document name. Console Image I want to display the name in my apps profile page. How would I achieve this?

Called it with this

Center(child:building(context),),
  Widget building(BuildContext context) {
    return new StreamBuilder(
        stream: Firestore.instance
            .collection('UserData')
            .document(getUID())
            .snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return new Text("Loading");
          } else {
            return new Text(snapshot.data.toString());
          }
        });
  }

Current Error Error Image

Previous Error

Error Message

Thanks in advance!

Upvotes: 0

Views: 2940

Answers (2)

John Joe
John Joe

Reputation: 12803

Try this

 Widget building(BuildContext context) {
    return new StreamBuilder<DocumentSnapshot>(
        stream: Firestore.instance
            .collection('UserData')
            .document('TjMJDFd940UtLORgdYND771GYwG2')
            .snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return new Text("Loading");
          } else {
            Map<String, dynamic> documentFields = snapshot.data.data;
            return Text(documentFields["First Name"] +
                " " +
                documentFields["Last Name"]);
          }
        });
  }

Note that TjMJDFd940UtLORgdYND771GYwG2 refer to documentID.

Upvotes: 1

Lewis
Lewis

Reputation: 4595

The docs for the Flutter Firebase API are stashed away and are admittedly hard to find. Here's the documentation on the QuerySnapshot class.

You are trying to look at the .document property of a QuerySnapshot object, so it's throwing an error because that property does not exist. Try using snapshot.documents to get a list of documents to iterate over (or just use snapshot.documents[0] if there will always only be one), and then read the data from that, i.e.: snapshot.documents[0].data[documentId]['First Name']. I removed quotes from documentId reference, since we want to index the variable value and not just the string "documentId".

Upvotes: 0

Related Questions