Future<List<List>> returns empty - Flutter

Viewed 73

I have a Future where users and posts are fetched from Firebase, turned into objects, added to either postsList or the usersList, and finally, the return is [usersList, postsList]. For so reason, though, the return looks like this when printed [[], []]. I think that the functions within are not completing before the return but I don't know how to fix that.

Here is the Future:

Future<List<QueryDocumentSnapshot>> getUserDocs() async {
    final userRef = FirebaseFirestore.instance.collection('users');
    final QuerySnapshot result = await userRef.get();
    final userDocs = result.docs;

    return Future.value(userDocs);
  }

  Future<List<QueryDocumentSnapshot>> getPostDocs() async {

    List<QueryDocumentSnapshot> userDocs = await getUserDocs();
    List<QueryDocumentSnapshot> postsDocs = [];

    for (final resultValue in userDocs) {
      final postsRef = FirebaseFirestore.instance
          .collection('users')
          .doc(resultValue.id)
          .collection('posts');
      final QuerySnapshot postsResult = await postsRef.get();
      final postDocs = postsResult.docs;

      print('postDocs: $postDocs');

      for (var post in postDocs) {
        postsDocs.add(post);
      }
    }
    return Future.value(postsDocs);
  }

  Future<List> fetchUsersAndPosts() async {

    List<QueryDocumentSnapshot> userDocs = await getUserDocs();
    List<QueryDocumentSnapshot> postsDocs = await getPostDocs();

    print('userDocs: $userDocs');
    print('postsDocs: $postsDocs');

    List<UserSearchResult> usersList = [];
    List<Post> postsList = [];

    for (var postsMap in postsDocs) {
      final post = Post.fromJson(postsMap.data() as Map<String, dynamic>);
      if (!postsList.contains(post)) {
        postsList.add(post);
      }
    }

    for (final value in userDocs) {
      final profileInfo =
      ProfileInfoObject.fromJson(value.data() as Map<String, dynamic>);

      Profile profile = Profile(
          profileInfo, postsList.where((p) => p.uid == value.id).toList());

      UserSearchResult user = (UserSearchResult(profile, value.id));

      if (usersList.where((u) => u.uid == user.uid).toList().isEmpty) {
        usersList.add(user);
        print('usersList: $usersList');
      }
    }

    postsList.sort((a, b) {
      return b.date.compareTo(a.date);
    });

    return [usersList, postsList];
  }
0 Answers
Related