Flutter Firebase reading Two Collection - Collection 2 dependant on 1

0

I have 2 collections on firebase.

Collection 1 Saves Users information shown in attach picture path on firebase-->'users/{usersId}')

Collection 2 stores UsersId of followers for each users path on firebase-->("/followers/{userId}/userFollowers/{followerId}")

enter image description here

Question: I will like to first read the usersId from followers collection then use the result (userId) to read the information of each individual users from Users collection and display the result.

I current made the code below but not sure if there is a best way of doing this. I have to put long delay in order to read even just 12 document from Firebase if not it only read few of them. Future.delayed(new Duration(milliseconds: 100)) if time is at 100 it displays on 4 result and if i put timer at 2000 it read all 12 documents. Is there better approach to this? is there any documentation that can help me understand this better.

Thanks in advance.

Below is my code for reading from firebase:

  Future<List<DocumentSnapshot>> getFollowersUsersInDB(
  String _currentUser) async {
List<DocumentSnapshot> userList = List<DocumentSnapshot>();
DocumentSnapshot t;

QuerySnapshot _ref =
    await followersRef.doc(_currentUser).collection("userFollowers").get();

_ref.docs.forEach((element) async {
  print(element.id.toString());
  t = await usersRef.doc(element.id.toString()).get();
  userList.add(t);
});
await new Future.delayed(new Duration(milliseconds: 100));
return userList;

}

Display of result code below:

_usersFollowers() {
return StreamBuilder(
    stream: 
        Stream.fromFuture(
            _authMethods.getFollowersUsersInDB(currentUser.id)),
    builder: (_context, _snapshot) {
      if (!_snapshot.hasData) {
        return circularProgress();
      } else {
        if (_snapshot.connectionState.index == 1 ||
            _snapshot.connectionState.index == 3) {
          print(_snapshot.connectionState.index.toString());
          var _userData = _snapshot.data;
          return Column(
            children: [
              Container(
                  height: SizeConfig.screenHeight * 0.5,
                  child: _userData.length != 0
                      ? ListView.builder(
                          itemCount: _userData.length,
                          itemBuilder: (BuildContext _context, _index) {
                            User users =
                                User.fromDocument(_userData[_index]);
                            // print(_userData.length.toString());
                            return ListTile(
                              title:
                                  //Text(_userData[_index].data["displayName"]),
                                  // Text(_userData[_index].displayName),
                                  Text(users.displayName),
                              leading: Container(
                                child: //_userData[_index].photoUrl != null &&
                                    //_userData[_index].photoUrl  != ""
                                    users.photoUrl != null &&
                                            users.photoUrl != ""
                                        ? CircleAvatar(
                                            radius: avatarSize,
                                            backgroundColor: Colors.grey,
                                            child: ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(50),
                                              child: Image(
                                                image:
                                                    CachedNetworkImageProvider(
                                                        users.photoUrl),
                                                fit: BoxFit.contain,
                                              ),
                                            ),
                                            //child: Image(image: CachedNetworkImageProvider(currSearchStuff[_index].data["photoUrl"]),fit:BoxFit.cover,),
                                            // backgroundImage: CachedNetworkImageProvider(currSearchStuff[_index].data["photoUrl"],),
                                          )
                                        : CircleAvatar(
                                            radius: avatarSize,
                                            backgroundColor: Colors.grey,
                                            child: Text(
                                              users.initials,
                                              textScaleFactor: 1,
                                              style: TextStyle(
                                                  fontSize:
                                                      avatarSize / 1.12,
                                                  color: Theme.of(context)
                                                      .primaryColor),
                                            ),
                                          ),
                                width: 2.5 * avatarSize,
                                height: 2.5 * avatarSize,
                                padding: const EdgeInsets.all(
                                    3.0), // borde width
                                decoration: BoxDecoration(
                                  color: const Color(
                                      0xFFFFFFFF), // border color
                                  shape: BoxShape.circle,
                                ),
                              ),
                              //,
                              subtitle: Text(users.jobtitle),
                            );
                          },
                        )
                      : Text("")),
            ],
          );
        }
        return circularProgress();
      }
    });

}

firebase
flutter
dart
stream-builder
flutter-futurebuilder
asked on Stack Overflow Sep 15, 2020 by K Safo • edited Sep 15, 2020 by K Safo

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0