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

Time:01-09

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?

CodePudding user response:

You need to cast the data to a map like this

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

CodePudding user response:

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.

  •  Tags:  
  • Related