Reputation: 361
My app has a collection of cards and I need to add some car to the favorites list, and I would like that each user has its own favorites collection.
So I did the classic StreamBuilder sample to show some list on Flutter:
StreamBuilder<QuerySnapshot>(
stream: getCars()
If the getCars() function is like this, everything is ok:
getCars() {
return Firestore.instance
.collection("users")
.document("oT646MvXXXXXXXXXXXjlN8L1V2")
.collection("cars").snapshots();
}
Let's say that "oT646MvXXXXXXXXXXXjlN8L1V2" is the FirebaseUser uid.
But how can I read FirebaseUser uid dinamically to return the collection?
I tried this code but it didn't work, since it returns a Future:
getCarsError() async { FirebaseUser fUser = await FirebaseAuth.instance.currentUser();
return Firestore.instance
.collection("users")
.document(fUser.uid)
.collection("cars").snapshots();
}
How can I acompplish that?
thank you
Upvotes: 0
Views: 336
Reputation: 788
Okay, the idea is to create a stream (I use the rxDart library but you can make it without)
BehaviorSubject<Car> _carController = BehaviorSubject<Car>();
Function(Car) get pushCar => _carController.sink.add;
Stream<Car> get streamCar => _carController ;
...
StreamBuilder<Car>(
stream: streamCar
Then in your async function:
void getCars() async{
FirebaseUser fUser = await FirebaseAuth.instance.currentUser();
Firestore.instance
.collection("users")
.document(fUser.uid)
.collection("cars").getDocuments().then((querySnapshot){
for (document in querySnapshot.documents){
pushCar(Car.fromJson(document.data)); //Deserialize your car here
}).catchError((e)=>print(e)); //Do what you want to handle error
}
So you push asynchronously your car into your stream, and you just get the stream<Car>
and print what you have to :)
Hope it's help !!
Upvotes: 1