getNumberOfFriends method

Future<int> getNumberOfFriends(
  1. String username
)

Fetch friends count for a given username @param username The username to search for friends @returns Amount of friends for the given username

Implementation

Future<int> getNumberOfFriends(String username) async {
  final querySnapshot = await FirebaseFirestore.instance
      .collection('users')
      .where('username', isEqualTo: username)
      .limit(1)
      .get();

  if (querySnapshot.docs.isEmpty) {
    return 0;
  }

  final documentRef = querySnapshot.docs.first.reference;
  final friendshipsRef = FirebaseFirestore.instance.collection('friendships');

  final acceptedSnapshot1 = await friendshipsRef
      .where('sender', isEqualTo: documentRef)
      .where('status', isEqualTo: 'accepted')
      .get();

  final acceptedSnapshot2 = await friendshipsRef
      .where('receiver', isEqualTo: documentRef)
      .where('status', isEqualTo: 'accepted')
      .get();

  final allDocs = [...acceptedSnapshot1.docs, ...acceptedSnapshot2.docs];

  return allDocs.length;
}