Andrii Pryimak
Andrii Pryimak

Reputation: 817

Can not get data from reference field in firebase (flutter)

I am trying to get data via reference field.

My code

DocumentReference docRef = FirebaseFirestore.instance
                        .doc(snapshot.data!.data()!["organisator"]);
                    docRef.get().then((DocumentSnapshot document) {
                      if (document.exists) {
                        print(document.data());
                      }
                    });

Print gives me this: {image: img_url, name: Dan Brown}

But when I try to get image or name like this document.data()!["image"] I always get an error:

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'.

I saw possible solution with document.data.data() but it returns me just an error.

So how can I actually get name or image properties from my response?

Upvotes: 0

Views: 284

Answers (2)

Andrii Pryimak
Andrii Pryimak

Reputation: 817

For anyone who will face same problem, this is my working code, based on Nathaniel Akubuo answer.

DocumentReference docRef = FirebaseFirestore.instance
                        .doc(snapshot.data!.data()!["organisator"]);
                    docRef.get().then((DocumentSnapshot document) {
                      if (document.exists) {
                        Map<String, dynamic> finData =
                            document.data() as Map<String, dynamic>;
                        print(finData["name"]); //Dan Brown output
                      }
                    });

As a result of print I successfully get the needed name value.

Upvotes: 0

Nathaniel Akubuo
Nathaniel Akubuo

Reputation: 36

You need to cast the data to a map like this

document.data() as Map<String, dynamic>

Upvotes: 1

Related Questions