I am trying to get all postID's of the currently logged in user from the left, and I want to use this information to get all posts which includes same postID. How can I achieve this?
So far I created a function that can pull all postID's of current user and put it in a list but I think I couldn't manage to work it. https://i.sstatic.net/ThfSm.png
List<String> myFavoritePosts = [];
Future<List<String>> getFavorites() async {
final FirebaseAuth auth = FirebaseAuth.instance;
final User? user = auth.currentUser;
final userID = user!.uid;
var result = await FirebaseFirestore.instance
.collection('favorites')
.where("userID", whereIn: [userID]).get();
for (var res in result.docs) {
myFavoritePosts.add((res.data()['postID'] ?? ''));
}
return myFavoritePosts;
}
But I couldn't implement it into my StreamBuilder structure.
Widget build(BuildContext context) {
final Stream<QuerySnapshot> _postStream = FirebaseFirestore.instance
.collection('Posts')
.where('postID',
isEqualTo:
getFavorites())
.snapshots();
return StreamBuilder<QuerySnapshot>(
stream: _postStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Please try again');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return ListView(
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return ListTile(
title: Text(data['title']),
subtitle: Column(
children: <Widget>[
Text(data['details']),
],
),
);
}).toList(),
);
How can I connect those two database so I can show the posts that have the same ID?
Use This:-
`
List<String> myFavoritePosts = [];
Future<List<String>> getFavorites() async {
var favourite;
final FirebaseAuth auth = FirebaseAuth.instance;
final User? user = auth.currentUser;
final userID = user!.uid;
var result = await FirebaseFirestore.instance
.collection('favorites')
.where("userID", whereIn: [userID]).get();
for (var res in result.docs) {
myFavoritePosts.add((res.data()['postID'] ?? ''));
}
myFavoritePosts.forEach((element){
favourite = element;
});
return favourite;
}`
And then:-
'Widget build(BuildContext context) {
final Stream<QuerySnapshot> _postStream = FirebaseFirestore.instance
.collection('Posts')
.where('postID',
isEqualTo:
getFavorites())
.snapshots();
return StreamBuilder<QuerySnapshot>(
stream: _postStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Please try again');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return ListView(
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return ListTile(
title: Text(data['title']),
subtitle: Column(
children: <Widget>[
Text(data['details']),
],
),
);
}).toList(),
);'