Flutter cloud firestore read data with reference

Viewed 200

Firestore collection chat has a field user_id it's type is reference and it refers to users collection document id. I want to use this reference to get user information from user collection like join in sql.

What I'm getting in my app.

{message: Hello Zia, user_id: DocumentReference(users/mfzfwKvXo5M5dFFuqKeM), event_id: DocumentReference(events/J3HTFRpL0HEbmMV2BSSb), time: Timestamp(seconds=1618466409, nanoseconds=0)}

My Code

ListView(
              children: snapshot.data.docs.map((DocumentSnapshot document) {
                print(document.data()['user_id']);
                try {
                  print(document.data()['user_id'].toString());
                } catch (e) {}
                return new ListTile(
                  leading: FutureBuilder<DocumentSnapshot>(
                    future: user.doc(**document.data()['user_id']**).get(),   
  // document.data()['user_id])  it's a DocumentReference.
                      builder: (BuildContext context,
                        AsyncSnapshot<DocumentSnapshot> snapshot) {
                      if (snapshot.hasError) {
                        return Text("Something went wrong");
                      }

                      if (snapshot.connectionState == ConnectionState.done) {
                        Map<String, dynamic> data = snapshot.data.data();
                        return Text(
                            "Full Name: ${data['full_name']} ${data['last_name']}");
                      }

                      return Text("loading");
                    },
                  ),
                  subtitle: new Text(document.data()['message']),
                  // subtitle: Text(document.data()['time']),
                );
              }).toList(),
            );

document.data()['user_id]) type 'DocumentReference' is not a subtype of type 'String'

1 Answers

I got the solution I'm posting solution it may helps others

document.data()['user_id].path

path properties return the path of the document

Related