My Firebase Form like this;
Users
User1 ID
- Posts
User2 ID
- Posts
The number of users changes according to the number of users in the application.
What I am trying to do is to show the posts of the users I have selected on my home screen.
So first of all I created a list like this(Users I want to show their posts);
List<dynamic> userIDs = [
"User1ID",
"User2ID"
];
Then I tried to use these elements in the list in a reference inside a for loop, Because I tried to show more than one user's post.
This is CollectionReference in for loop;
final firestore = FirebaseFirestore.instance;
var userPostsRef;
for (int i = 0; i < userIDs.length; i ) {
userPostsRef = userPostsRef.firestore.collection('users/${userIDs[i]}/Posts');
}
But it didn't work.
When I use CollectionReference like this;
var userPostsRef = firestore.collection('users/${userIDs[0]}/Posts');
It worked but I dont want to show single user posts, I want to show multiple users posts.
How can I show multiple users' posts on my home screen with this method or a different method?
CodePudding user response:
There is no way to load from the Posts
subcollections from a list of UIDs and not from others.
The closest that Firestore supports is loading from all Posts
collections with a collection group query, or from all Posts
subcollections under a specific path with the trick samthecodingman showed here: CollectionGroupQuery but limit search to subcollections under a particular document
If you can't change your data model to allow getting the data from the relevant subcollections with a single query, you will have to execute multiple queries and merge the results in your application code.
CodePudding user response:
You cant use query collection reference like this
var userPostsRef = firestore.collection('users/${userIDs[0]}/Posts');
my trick I used for my app
if you want to load all post under user id I recommend to wrap future builder (post list) under future builder (user list)
the other way is set user id with something you can track like (I use firebase.auth.email for document id reference so query will be easier)
or You can get all user id reference at the start of app and put that in memory variable so you can reduce redundancy get user id reference for the rest of functionality (mind about delete/changed user etc)
the other way around is make a dynamic query based on user action (this need more work around base on ur app)