0

in my flutter project I have 2 two firestore collections one is users collection where I have stored all user details, another collection is followers in it for each user there is a subcollection with his/her followers userid as documents. My question is how can I retrieve details of those followers from users collection?

Here is my users collection

users

Here is followers collection followers

2 Answers2

0

To read a collection or document once use Get Query

You can wrap GetUserName with a listview builder and pass userId.



class GetUserName extends StatelessWidget {
  final String documentId;

  GetUserName(this.documentId);

  @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('users');

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.hasData && !snapshot.data!.exists) {
          return Text("Document does not exist");
        }

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

        return Text("loading");
      },
    );
  }
}
Sahil Hariyani
  • 1,078
  • 3
  • 11
0

I think that you're structuring your data as if you were working in a relational database. Firestore doesn't support foreign keys like SQL databases, so you can't retrieve nested data like SQL. Firestore is a no-SQL database that doesn't have any notion of reference. See Firestore data model.

In Firestore, relationships are usually modeled by storing the id of the document you'd like to "reference". In that sense you might not need to store the 'users' document inside the ‘followers’ but the field 'user_id' would suffice( which you are trying to do). The caveat is that this data layout comes at the price of having to fetch the 'user_id' from ‘followers’ before you can fetch the actual user data. You could read more about data denormalization and modeling relationships in articles link1 , link2 and this other thread.

In Firestore you need to fetch referenced data separately, either you can fetch all users data separately in parallel with followers data and store it in map, or if you don't need users data initially then fetch each users data when needed like when you check details of each followers.

Priyashree Bhadra
  • 3,182
  • 6
  • 23